使用opencv捕获单张图片
我看到过很多关于用Python和OpenCV从网络摄像头流中捕捉画面的内容。但是,怎么才能用Python和OpenCV只捕捉一张指定分辨率的照片呢?
3 个回答
1
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序中使用这些数据。这个过程可能会涉及到很多步骤,比如连接数据库、查询数据、处理数据等等。
有些时候,程序在运行的时候可能会出现错误,这些错误可能是因为我们在处理数据时没有按照正确的方式来做。比如说,数据的格式不对,或者我们请求的数据不存在等等。
为了避免这些错误,我们可以在程序中加入一些检查的步骤,这样在出错之前就能发现问题。这样可以让我们的程序更加稳定,也能提高用户的体验。
总之,处理数据的时候要小心,确保每一步都做对了,这样才能让程序顺利运行。
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)
3
使用 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)
不过我不知道怎么关闭相机。
下面是一个使用上面代码的 ipython 会话示例:
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
11
你可以通过使用OpenCV的VideoCapture
方法来捕捉一帧画面。
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()
之后,你可以很简单地使用PIL来修改画面的分辨率。