本文介绍了Python:如何使用 OpenCV 在单击时从网络摄像头捕获图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 OpenCV 从我的网络摄像头捕获并保存大量图像.这是我目前的代码:

I want to capture and save a number of images from my webcam using OpenCV. This is my code currently:

import cv2

camera = cv2.VideoCapture(0)
for i in range(10):
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
del(camera)

这样做的问题是我不知道图像是什么时候拍摄的,所以很多图像最终都变得模糊不清.我的问题是:有没有办法在点击键盘键时拍摄图像?

The problem with this is that I do not know when the images are being taken, so a lot of them end up blurry. My question is: Is there a way to have the image taken on the click of a keyboard key?

还有没有更好的方法来拍摄多张图像而不是范围?

Also is there a better way to take multiple images, instead of range?

推荐答案

这里有一个简单的程序,它在 cv2.namedWindow 中显示相机源,并在您点击 时拍摄快照空格.如果你点击 ESC,它也会退出.

Here is a simple program that displays the camera feed in a cv2.namedWindow and will take a snapshot when you hit SPACE. It will also quit if you hit ESC.

import cv2

cam = cv2.VideoCapture(0)

cv2.namedWindow("test")

img_counter = 0

while True:
    ret, frame = cam.read()
    if not ret:
        print("failed to grab frame")
        break
    cv2.imshow("test", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        # SPACE pressed
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1

cam.release()

cv2.destroyAllWindows()

我认为这应该在很大程度上回答您的问题.如果您有任何不明白的地方,请告诉我,我会添加评论.

I think this should answer your question for the most part. If there is any line of it that you don't understand let me know and I'll add comments.

如果您需要每次按 SPACE 键抓取多张图片,您将需要一个内部循环,或者可能只是创建一个抓取一定数量图片的函数.

If you need to grab multiple images per press of the SPACE key, you will need an inner loop or perhaps just make a function that grabs a certain number of images.

注意关键事件来自 cv2.namedWindow 所以它必须有焦点.

Note that the key events are from the cv2.namedWindow so it has to have focus.

这篇关于Python:如何使用 OpenCV 在单击时从网络摄像头捕获图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 04:41