我有一个视频,我想从中提取所有帧并将它们保存为png图像,所以我做了以下操作:
nm ='1.mp4'
cap = cv2.VideoCapture(nm))
while cap.isOpened():
pos = cap.get(cv2.CAP_PROP_POS_FRAMES)
print pos
fn = nm.split('.')[0] + '_' + str(int(pos))
ext = nm.split('.')[1]
ret, frame = cap.read()
pth = os.path.join(base_folder, 'frames', fn + '.png')
if ret:
img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if cv2.countNonZero(cv2.calcHist([img], [0], None, [256], [0, 256])) > 1:
cv2.imwrite(pth, frame)
else:
break
cap.release()
然后我想根据它们的位置编号读取特定的帧并将其保存为png图像,所以我这样做了:
kframes_pos = [100, 201, 281]
for k in kframes_pos:
print k
sp = nm.split('.')
cap = cv2.VideoCapture(nm)
cap.set(cv2.CAP_PROP_POS_FRAMES, int(k))
fn = sp[0] + '_' + str(int(k))
ret, frame = cap.read()
if ret:
cv2.imwrite('ff/' + fn + '.png', frame)
当我目视比较这两种方法保存的图像时,即使它们具有相同的名称(图像名称为videoname_framePosition),它们也不相同,因此我得出结论cap.set与cap.read不会基于返回正确的帧位置传递给cap.set 如何解决呢?怎么了?