我正在使用以下代码来读取和计算文件夹中连续图像之间的差异:
def cal_for_frames(video_path):
frames = glob(os.path.join(video_path, '*.jpg'))
frames.sort()
diff = []
prev = cv2.imread(frames[0])
prev = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
print(prev.dtype, prev.shape)
for i, frame_curr in enumerate(frames):
curr = cv2.imread(frame_curr)
curr = cv2.cvtColor(curr, cv2.COLOR_BGR2GRAY)
print(curr.dtype, curr.shape)
tmp_diff = compute_DIFF(prev, curr)
diff.append(tmp_diff)
prev = curr
return diff
现在我希望prev
始终是文件夹中的第一张图片(即保持不变)。为此,我需要对prev = cv2.imread(frames[0])
进行哪些更改?其中frame000001
是文件夹中的第一张图像。 最佳答案
只需删除for-loop
的最后一行:prev = curr
和prev = cv2.imread(frames[0])
即可。
但是您可以加快for-loop
的速度。如果print
函数不是至关重要的,则可以执行以下操作:
diff = [compute_DIFF(prev, cv2.cvtColor(cv2.imread(frame_curr), cv2.COLOR_BGR2GRAY)) for i, frame_curr in enumerate(frames)]
码:def cal_for_frames(video_path):
frames = glob(os.path.join(video_path, '*.jpg')).sort()
prev = cv2.cvtColor(cv2.imread(frames[0]), cv2.COLOR_BGR2GRAY)
print(prev.dtype, prev.shape)
diff = [compute_DIFF(prev, cv2.cvtColor(cv2.imread(frame_curr), cv2.COLOR_BGR2GRAY)) for i, frame_curr in enumerate(frames)]
return diff
关于python-3.x - 如何使用OpenCV读取文件夹中的第一张图像(Python),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64611642/