Python 用opencv捕获单张图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4179220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:38:34  来源:igfitidea点击:

Capture single picture with opencv

pythonimageopencv

提问by a sandwhich

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?

我已经看到了一些关于使用 python 和 opencv 从网络摄像头流捕获帧的事情,但是如何使用 python 和 opencv 仅以指定的分辨率捕获一张图片?

回答by meduz

Use SetCaptureProperty :

使用 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 :

使用上述代码的 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

回答by akshaynagpal

You can capture a single frame by using the VideoCapturemethod of OpenCV.

您可以使用VideoCaptureOpenCV的方法捕获单个帧。

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.

稍后您可以使用PIL轻松修改分辨率。

回答by Sreeragh A R

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)