直接获取相机截图的方法

Direct way to get camera screenshot

我正在使用 Python OpenCV 进行一个项目,该项目的初始步骤涉及从网络摄像头捕获图像;我尝试使用 capture = cv2.VideoCapturecapture.read() 来自动化这个过程,但是相机的视频模式激活和随后的自我调整对于我最终想要实现的目标来说太慢了。

是否有更直接的方法可以使用 Python(和 OpenCV)自动捕获屏幕截图?如果没有,您有其他建议吗? 谢谢

基本上你需要做三件事:

#init the cam
video_capture = cv2.VideoCapture(0)
#get a frame from cam
ret, frame = video_capture.read()
#write that to disk
cv2.imwrite('screenshot.png',frame)

当然,你应该先等一会儿,否则你可以保存一个奇怪的黑屏(或者只是相机得到的第一件事:-))

如果你想让你的相机截图功能响应,你需要初始化相机截图 outside 这个函数。

在以下代码片段中,screenshot 函数是通过按 c 触发的:

import cv2

def screenshot():
    global cam
    cv2.imshow("screenshot", cam.read()[1]) # shows the screenshot directly
    #cv2.imwrite('screenshot.png',cam.read()[1]) # or saves it to disk

if __name__ == '__main__':

    cam = cv2.VideoCapture(0) # initializes video capture

    while True:
        ret, img = cam.read()
        cv2.imshow("cameraFeed", img) # a window is needed as a context for key capturing (here, I display the camera feed, but there could be anything in the window)
        ch = cv2.waitKey(5)
        if ch == 27:
            break
        if ch == ord('c'): # calls screenshot function when 'c' is pressed
            screenshot()

    cv2.destroyAllWindows()

澄清一下cameraFeed window 仅用于演示目的(其中 screenshot 是手动触发的)。如果screenshot在你的程序中自动调用,那么你不需要这部分。

希望对您有所帮助!