如何使用opencv和python以千帧为单位打印1?

2024-05-01 21:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在每一千帧的视频中保存一帧。下面是我目前使用的代码:

import cv2
import numpy as np
import os
# Playing video from file:
cap = cv2.VideoCapture('D:/01 Projects/AMAZON CATALYST PROJECT/Surgery1.mpg')
try:
    if not os.path.exists('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1'):
    os.makedirs('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1')
except OSError:
    print ('Error: Creating directory of data_surg1')
currentFrame = 0
while(True):
    # Capture frame-by-frame
    if currentFrame > 0:
        cap.set(cv2.CAP_PROP_POS_MSEC,currentFrame) 
    ret, frame = cap.read()

    # Saves image of the current frame in jpg file
    name = 'D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1/frame' + str(currentFrame/1000) + '.jpg'
    print ('Creating...' + name)
    cv2.imwrite(name, frame)

    # To stop duplicate images
    currentFrame += 1000

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

但是,我不确定这是否保存正确。当我在文件资源管理器中查看帧时,数字最初非常高,然后与上一个图像相比减少,形成一个连续的帧编号。我使用的是python2.7和OpenCV3.3。你知道吗


Tags: nameimportprojectamazondataifoscv2
1条回答
网友
1楼 · 发布于 2024-05-01 21:45:30

对于从特定帧存储而不是基于时间的存储,以下脚本起作用:

import cv2
import numpy as np
import os
# Playing video from file:
cap = cv2.VideoCapture('D:/01 Projects/AMAZON CATALYST PROJECT/Surgery1.mpg')
try:
    if not os.path.exists('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1'):
    os.makedirs('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1')
except OSError:
    print ('Error: Creating directory of data_surg1')
currentFrame = 0
while(True):
    # Capture frame-by-frame
    if currentFrame > 0:
        cap.set(cv2.CAP_PROP_POS_FRAMES,currentFrame) 
    ret, frame = cap.read()

    # Saves image of the current frame in jpg file
    name = 'D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1/frame' + str(currentFrame/1000) + '.jpg'
    print ('Creating...' + name)
    cv2.imwrite(name, frame)

    # To stop duplicate images
    currentFrame += 1

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

相关问题 更多 >