I have seen several things about capturing frames from a webcam stream using python and opencv, But how do you capture only one picture at a specified resolution with python and opencv?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can capture a single frame by using the VideoCapture
method of OpenCV.
import numpy as np
import cv2
cap = cv2.VideoCapture(0) # video capture source camera (Here webcam of laptop)
ret,frame = cap.read() # return a single frame in variable `frame`
while(True):
cv2.imshow('img1',frame) #display the captured image
if cv2.waitKey(1) & 0xFF == ord('y'): #save on pressing 'y'
cv2.imwrite('images/c1.png',frame)
cv2.destroyAllWindows()
break
cap.release()
Later you can modify the resolution easily using PIL.
回答2:
Use SetCaptureProperty :
import cv
capture = cv.CaptureFromCAM(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, my_height)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, my_width)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FORMAT, cv.IPL_DEPTH_32F)
img = cv.QueryFrame(capture)
Do not know how to close the camera, though.
Example of a ipython session with the above code :
In [1]: import cv
In [2]: capture = cv.CaptureFromCAM(0)
In [7]: img = cv.QueryFrame(capture)
In [8]: print img.height, img.width
480 640
In [9]: cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480/2)
Out[9]: 1
In [10]: cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640/2)
Out[10]: 1
In [11]: img = cv.QueryFrame(capture)
In [12]: print img.height, img.width
240 320
回答3:
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,640) #width=640
cap.set(4,480) #height=480
if cap.isOpened():
_,frame = cap.read()
cap.release() #releasing camera immediately after capturing picture
if _ and frame is not None:
cv2.imwrite('img.jpg', frame)
cv2.imwrite(name, frame)