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

20 python opencv python-2.7

我想使用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)
Run Code Online (Sandbox Code Playgroud)

这个问题是我不知道什么时候拍摄这些照片,所以很多照片都会模糊不清.我的问题是:有没有办法在点击键盘键上拍摄图像?

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

der*_*icw 39

这是一个简单的程序,可以显示摄像机输入,cv2.namedWindow并在您点击时拍摄快照SPACE.如果你击中它也会退出ESC.

import cv2

cam = cv2.VideoCapture(0)

cv2.namedWindow("test")

img_counter = 0

while True:
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    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()
Run Code Online (Sandbox Code Playgroud)

我认为这应该在很大程度上回答你的问题.如果有任何你不明白的行让我知道,我会添加评论.

如果每按一次SPACE键需要抓取多个图像,则需要一个内循环或者只需要创建一个抓取一定数量图像的函数.

请注意,关键事件来自于cv2.namedWindow它必须具有焦点.


Hen*_*rik 8

分解您的代码示例(说明在代码行下方。)

import cv2
Run Code Online (Sandbox Code Playgroud)

导入 openCV 以供使用

camera = cv2.VideoCapture(0)
Run Code Online (Sandbox Code Playgroud)

使用连接到计算机的相机列表中的第一个相机创建一个名为相机的对象,类型为 openCV 视频捕获。

for i in range(10):
Run Code Online (Sandbox Code Playgroud)

告诉程序将以下缩进代码循环 10 次

    return_value, image = camera.read()
Run Code Online (Sandbox Code Playgroud)

使用它的 read 方法从相机对象读取值。它与 2 个值产生共鸣,将 2 个数据值保存到两个名为“return_value”和“image”的临时变量中

    cv2.imwrite('opencv'+str(i)+'.png', image)
Run Code Online (Sandbox Code Playgroud)

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

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

del(camera)
Run Code Online (Sandbox Code Playgroud)

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

您可以通过多种方式满足您的要求,其中一种可能是用 while 循环替换 for 循环(永远运行,而不是 10 次),然后等待按键(例如在我打字时由danidee回答)

或者创建一个隐藏在后台并在每次有人按下键盘时捕获图像的更邪恶的服务......


dan*_*dee 5

我对 open cv 不太有经验,但如果您希望按下按键时调用 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)
Run Code Online (Sandbox Code Playgroud)


Ant*_*ntu 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()
Run Code Online (Sandbox Code Playgroud)

输出

在此输入图像描述

另外,你可以查看我的 GitHub代码

  • 这并不能回答问题。 (3认同)