Python 2.7 / OpenCV 3.3:从立体摄像机捕获帧

时间:2017-09-05 06:11:09

标签: python-2.7 opencv3.0 camera-calibration stereo-3d

我正在使用Python 2.7和OpenCV 3.3,并希望在每个定义的帧数或定义的秒后保存立体相机中的图像。像每隔5帧或每2秒帧一样,应存储在不同的文件夹中,如 cam1folder cam2folder 。我可以从两个摄像头捕获视频,然后使用这些视频在预定义的秒后捕获帧。这些代码如下。

视频捕获代码:

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
cap1 = cv2.VideoCapture(1)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out1 = cv2.VideoWriter('output1.avi',fourcc, 20.0, (640,480))

while(True):
    ret, frame = cap.read()
    ret1, frame1 = cap1.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    out.write(frame)
    out1.write(frame1)
    cv2.imshow('frame',gray)
    cv2.imshow('frame1', frame1)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cap1.release()
out1.release()
cv2.destroyAllWindows()

保存视频后从两台相机捕获的帧的代码:

import cv2
import math
import numpy as np
videoFile = "output.avi"
vidcap = cv2.VideoCapture(videoFile)
success,image = vidcap.read()

videoFile1 = "output1.avi"
vidcap1 = cv2.VideoCapture(videoFile1)
success1,image1 = vidcap1.read()

seconds = 3
fps = vidcap.get(cv2.CAP_PROP_FPS) # Gets the frames per second
multiplier = fps * seconds
fps1 = vidcap1.get(cv2.CAP_PROP_FPS) # Gets the frames per second
multiplier1 = fps1 * seconds


while success:
    frameId = int(round(vidcap.get(1))) #current frame number, rounded b/c sometimes you get frame intervals which aren't integers...this adds a little imprecision but is likely good enough
    success, image = vidcap.read()

    frameId1 = int(round(vidcap1.get(1)))  #current frame number
    success1, image1 = vidcap1.read()

    if frameId % multiplier == 0:
        cv2.imwrite("right/rframe%d.jpg" % frameId, image) # stored in right folder
    if frameId1 % multiplier1 == 0:
        cv2.imwrite("left/lframe%d.jpg" % frameId1, image1) # stored in left folder


vidcap.release()
vidcap1.release()
print "Complete"

但我想要的是直接从视频中实时捕捉图像而不保存这些视频,而是将拍摄的图像保存在两个不同的文件夹中。怎么做?

感谢。

1 个答案:

答案 0 :(得分:0)

您只需要合并自己编写的2个代码段。

在您的第一个代码段中,当您运行while循环时,您可以维护一个公共计数器,而不是单独的摄像头的单独计数器。当您的计数器达到所需值(5帧,根据您的问题)时,您可以直接在imwriteframe对象上执行frame1

您不需要使用VideoWriter对象进行中间处理。 您的最终代码如下所示:

cap = cv2.VideoCapture(0)
cap1 = cv2.VideoCapture(1)
multiplier = 5
frame_count = 0
while(True):
    frame_count += 1
    ret, frame = cap.read()
    ret1, frame1 = cap1.read()

    cv2.imshow('frame',frame)  #show all frames
    cv2.imshow('frame1', frame1)

    if frame_count % multiplier == 0:
        cv2.imwrite("right/rframe%d.jpg" % frame_count, frame) #write specific frames 
        cv2.imwrite("left/lframe%d.jpg" % frame_count, frame1)

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