使用opencv使用python使用网络摄像头(外部或内部)拍摄快照

时间:2016-10-22 01:13:16

标签: python

我是新来的,也是opencv的新手。  我手边有这个项目 - 设计一个能够与我的计算机网络摄像头连接并拍摄快照并录制视频的应用程序。 到目前为止,我可以这么好,

import cv2 as cv
import numpy 

cv.namedWindow ("camera", 1)

capture = cv.VideoCapture (0)

while True:
    ret, frame = capture.read ()
    img = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
    cv.imshow ("camera", img)
    if cv.waitKey(10) & 0XFF == ord ("q")
        break
capture.release ()
cv.destroyAllWindows ()

现在我想我想使用cv.VideoCapture.grab() 并且cv.VideoCapture.retrieve() 但说实话,我不知道如何使用。 我需要你的帮助

3 个答案:

答案 0 :(得分:0)

这里有一个很好的例子:

http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html

以下示例将每30秒拍摄一张快照并将其保存到具有唯一时间戳的文件中:

import cv2 as cv
import time
import datetime

cv.namedWindow("camera", 1)
capture  = cv.VideoCapture(0)

while True:
    ret, frame = capture.read ()
    frame = cv.cvtColor (frame,  cv.COLOR_BGR2BGRA) 

    file = "C:\Python34\CpV\%s.png" %  datetime.datetime.now().strftime("%d-%m-%y--%H-%M-%S")
    cv.imwrite (file, frame)
    #cv.imshow("camera", frame)

    time.sleep(30)
capture.release()
cv.destroyAllWindows ()

答案 1 :(得分:0)

好的,我必须编辑我的代码并且它有效 看看

import cv2 as cv
import time

cv.namedWindow("camera", 1)
capture  = cv.VideoCapture(0)

while True:
    ret, frame = capture.read ()
    frame = cv.cvtColor (frame,  cv.COLOR_BGR2BGRA) 

    file = "C:\Python34\CpV\test.png"
    cv.imwrite (file, frame)
    cv.imshow("camera", frame)

    #it takes a snapshot when "q" is pressed and closes
    the window
    if cv.waitKey(10) & 0xFF == ord ('q'):
        break
capture.release()
cv.destroyAllWindows ()

据我所知,我需要编辑一点,以使其简洁明了。下一个问题是从网络摄像头录制视频。

所以我仍然需要你的帮助。提前谢谢。

答案 2 :(得分:0)

使用以下代码将网络摄像头捕获记录到文件:

import cv2
import cv
cap = cv2.VideoCapture(0)
ret,img=cap.read()
height , width , layers =  img.shape     
fps=20
video = cv2.VideoWriter("rec_out.avi", cv.CV_FOURCC(*'DIVX'), fps, (img.shape[1], img.shape[0]))
while True: 

    ret,img=cap.read()
    height , width , layers =  img.shape
        video.write(img)
    cv2.imshow('Video', img)
    #video.write(img)
    if(cv2.waitKey(10) & 0xFF == ord('b')):
            break