【问题标题】:Auto-capture an image from a video in OpenCV using python使用 python 从 OpenCV 中的视频中自动捕获图像
【发布时间】:2014-08-25 19:30:57
【问题描述】:

我正在尝试开发一个用作自拍相机的代码。视频将在窗口中显示,并且将不断检测人的面部和眼睛,一旦用户选择特定时间,就会捕获该时间点的帧。我可以使用时间模块中的睡眠功能在一段时间后捕获帧,但视频帧似乎冻结了。是否有任何解决方案可以让我继续观看视频,并且视频捕获会在一段时间后自动进行。

我正在使用代码-

import numpy as np
import cv2
import time
import cv2.cv as cv
cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

# Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

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

#time.sleep(01)
    Capture = cv.CaptureFromCAM(0)
    time.sleep(5)
    ret, frame = cap.read()
    image = cv.QueryFrame(Capture) #here you have an IplImage
    imgarray = np.asarray(image[:,:]) #this is the way I use to convert it to numpy array

    cv2.imshow('capImage', imgarray)
    cv2.waitKey(0)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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

有人可以推荐我吗?任何形式的帮助将不胜感激。

【问题讨论】:

  • 请删除帖子中所有不必要的代码
  • 我删除了代码的人脸检测部分。只剩下必要的部分了
  • 为什么它对同一个 id 使用 2 个视频捕获? Capture = cv.CaptureFromCAM(0) 将失败,因为它已经在使用中。请坚持使用 cv2 api,旧的 cv 不应该再使用了

标签: python opencv python-3.x video-capture face-detection


【解决方案1】:

为了连续观看视频,您需要重复首先显示视频的同一部分代码并将其放入while循环中。确保窗口的句柄没有丢失。您可以将捕获作为鼠标单击事件并使用滴答计数,一个在 while 循环开始之前,一个在循环内部。一旦两个滴答计数之间的差异等于某个预定义的秒数,则捕获该帧,使用 break 并退出 while 循环。

【讨论】:

    【解决方案2】:

    您需要在延迟结束时添加另一个“cap.read()”行,因为这是实际捕获图像的代码。

    【讨论】:

    • 是的,它可以工作,但我想看视频。一旦调用 sleep,视频帧就会冻结。我希望它可以用作手机的自拍定时器。
    【解决方案3】:

    使用线程并与您的函数分开定义 cv.imshow()

    import threading
    import cv2
    def getFrame():
        global frame
        while True:
            frame = video_capture.read()[1]
    
    def face_analyse():
        while True:
    #do some of the opeartion you want  
    
    def realtime():
        while True:
            cv2.imshow('Video', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                video_capture.release()
                cv2.destroyAllWindows()
                break
    
    if __name__ == "__main__":
        video_capture = cv2.VideoCapture(cam)
        frame = video_capture.read()[1]
    
        gfthread = threading.Thread(target=getFrame, args='')
        gfthread.daemon = True
        gfthread.start()
        rtthread = threading.Thread(target=realtime, args='')
        rtthread.daemon = True
        rtthread.start()
        fathread = threading.Thread(target=face_analyse, args='')
        fathread.daemon = True
        fathread.start()
    
        while True: #keep main thread running while the other two threads are non-daemon
            pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 2017-08-20
      • 2022-11-02
      • 2020-12-19
      • 2019-06-15
      • 1970-01-01
      相关资源
      最近更新 更多