Python: 如何使用OpenCV在单击时从网络摄像头捕获图像

58
我想使用OpenCV从我的网络摄像头中捕获并保存多张图像。这是我目前的代码:
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)

这个问题在于我不知道何时拍摄图像,因此很多图像最终变得模糊。我的问题是:是否有一种方法可以在按下键盘键时拍摄图像?

另外,是否有更好的方法来拍摄多张图像,而不是使用范围?


我认为没有必要使用 del(camera) - TheTridentGuy
5个回答

106

这里是一个简单的程序,它会在 cv2.namedWindow 中显示相机的视频流,并在你按下 SPACE 键时拍摄快照。如果你按下 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()

我认为这应该大部分回答了你的问题。如果有任何一行你不理解,请告诉我,我会添加注释。

如果你需要在每次按下SPACE键时抓取多个图像,你需要一个内部循环或者可能只需制作一个函数来获取一定数量的图像。

请注意,关键事件来自于cv2.namedWindow,因此它必须获得焦点。


如果您包含了人们可以更改存储这些图像位置的代码行,那就更完整了。无论如何,做得很好! - Chau Loi
如果在流式窗口上按下X键,是否可以中断循环? - The Hog
1
@TheHog https://dev59.com/7WYr5IYBdhLWcg3w6OGd - derricw

10

解析您的代码示例(代码下面有解释。)

import cv2

导入OpenCV以供使用

camera = cv2.VideoCapture(0)

创建一个叫做camera的对象,类型为openCV视频捕获,使用连接到计算机的摄像头列表中的第一个摄像头。

for i in range(10):

告诉程序循环执行下面缩进的代码10次。

    return_value, image = camera.read()

使用摄像头对象的read方法读取值,它会返回2个值。将这2个数据值保存到名为"return_value"和"image"的两个临时变量中。

    cv2.imwrite('opencv'+str(i)+'.png', image)

使用OpenCV方法imwrite(将图像写入磁盘)并使用临时数据变量中的数据编写图像

较少的缩进意味着循环现在已经结束...

del(camera)

删除相机对象,我们不再需要它。

你可以用多种方式实现你的请求,其中一种方法是将for循环替换为while循环(无限运行而不是10次),然后等待按键(就像我在打字时被danidee回答的那样)。

或者创建一个更加恶意的服务,隐藏在后台,每次有人按键时捕获一张图片......


5

我对OpenCV并不太有经验,但如果您希望在按下某个键时调用for循环中的代码,您可以使用while循环、raw_input以及条件来防止循环永远执行。

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

1
如果你正在使用Python3,请将“raw_input()”函数更改为“input()”函数。 - M.Hossein Rahimi

5

这是一个简单的程序,可以使用默认相机拍摄图像。 此外,它可以检测人脸。

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('s'): 

        check, frame = video_capture.read()
        cv2.imshow("Capturing", frame)
        cv2.imwrite(filename='saved_img.jpg', img=frame)
        video_capture.release()
        img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
        img_new = cv2.imshow("Captured Image", img_new)
        cv2.waitKey(1650)
        print("Image Saved")
        print("Program End")
        cv2.destroyAllWindows()

        break
    elif cv2.waitKey(1) & 0xFF == ord('q'):
        print("Turning off camera.")
        video_capture.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

输出

这里输入图片描述

此外,你可以查看我在 GitHub 上的代码


3
这并没有回答这个问题。 - Jacob Jones

2

这是一个简单的程序,可以使用笔记本电脑默认摄像头捕获图像。我希望这对所有人来说都是非常简单的方法。

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame = video.read()
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 5.show the frame!
    cv2.imshow("Capturing",frame)
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows 

你可以在这里查看我的Github代码here

谢谢。@机器人,现在你可以检查了。 - Humayun Ahmad Rajib

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接