本文介绍了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中显示照相机源,并在您按下SPACE时拍摄快照.如果您按下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