use*_*423 2 python opencv image-capture image-processing cv2
我正在尝试构建一个简短的脚本,用我的立体相机拍摄多张图像,并在我按下按钮时将它们保存到一个目录中。
但出于某种原因,即使我拍了多张照片,我也只能得到最后一张照片。它也没有显示任何错误并打印出我在代码中编写的正确字符串。但我得到的只是最后一个图像对。
我看了几个帖子,但没有一个有同样的问题。
编辑:我没有像这里的每个人建议的那样在图像名称中添加秒数,因此图像在同一分钟拍摄时被覆盖。
如果有人想使用它,这是我现在完成的代码:
import numpy as np
import cv2
import os
import datetime
# shape of wholeFrame: (240, 640, 3)
cap = cv2.VideoCapture(1)
now = 0
imgs_taken = 0
newpath_l = "Recorded_Images/left_imgs"
newpath_r = "Recorded_Images/right_imgs"
newpath = "Recorded_Images/both_imgs"
if not os.path.exists(newpath_l):
os.makedirs(newpath_l)
if not os.path.exists(newpath_r):
os.makedirs(newpath_r)
if not os.path.exists(newpath):
os.makedirs(newpath)
while 1:
cap.grab()
ret, wholeFrame = cap.retrieve()
if ret:
leftFrame = wholeFrame[:, 0:320, :]
rightFrame = wholeFrame[:, 320:640, :]
# Rectifying images here
stereoImage = np.concatenate((leftFrame, rightFrame), axis=1)
cv2.imshow('Take Snapshots', stereoImage)
key = cv2.waitKey(1) & 0xFF
# Saving images on keypress with timestamp
if key == ord('p'):
now = datetime.datetime.now()
if not cv2.imwrite(newpath_l + now.strftime("/img_left_%d%m%Y_%H%M%S.png"), leftFrame):
print("Left Snapshot not taken")
else:
print("Left Snapshot taken.")
if not cv2.imwrite(newpath_r + now.strftime("/img_right_%d%m%Y_%H%M%S.png"), rightFrame):
print("Right Snapshot not taken")
else:
print("Right Snapshot taken.")
if not cv2.imwrite(newpath + now.strftime("/img_both_%d%m%Y_%H%M%S.png"), stereoImage):
print("Stereo-Snapshot not taken")
else:
print("Stereo-Snapshot taken.")
imgs_taken = imgs_taken + 1
if key == ord('x'):
print("Number of images taken: " + str(imgs_taken))
break
else:
break
cv2.destroyAllWindows()
cap.release()
Run Code Online (Sandbox Code Playgroud)
小智 5
cv2.imwrite本身没有问题,而在于您如何命名要保存的框架。您将帧命名为日 + 月 + 年 _ 小时 + 分钟。这意味着您在给定分钟内保存的任何帧都将被该分钟内保存的最后一帧覆盖。例如,在 19:00:23 保存的帧将被保存在 19:00:34 的帧覆盖。根据您的用例,您可以添加+ now.strftime("%S")以每秒保存一帧,或者您甚至可以添加+ now.strftime("%S_%f")毫秒精度。