无法使用videoCapture opencv打开视频

2024-09-29 21:22:22 发布

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

我有以下代码从视频文件中读取帧并存储为jpg。如果我直接从相机读取帧,代码工作正常,但对于视频文件,它不会读取帧

cap = cv2.VideoCapture('C:/Users/lostpanda.mp4')
#cap = cv2.VideoCapture(0)
count = 0
while cap.isOpened():
  ret,frame = cap.read()
  print(ret,frame)
  cv2.imshow('window-name', frame)
  name = 'C:/Users/video_testing/video-frames/' + str(count) + '.jpg'
  #cv2.imwrite("frame%d.jpg" % count, frame)
  cv2.imwrite(name,frame)
  count = count + 1
  if cv2.waitKey(10) & 0xFF == ord('q'):
    break

谢谢


Tags: 代码namevideocountcv2frameusersjpg
1条回答
网友
1楼 · 发布于 2024-09-29 21:22:22

您可以尝试以下方法:

import cv2 
import os 

# Read the video from specified path 
cam =cv2.VideoCapture(r"C:/Users/lostpanda.mp4") 

try:
    # creating a folder named data 
    if not os.path.exists('video-frames'): 
        os.makedirs('video-frames') 

# if not created then raise error 
except OSError: 
    print ('Error: Creating directory of data') 

# frame 
currentframe = 0

while(True): 
  
# reading from frame 
    ret,frame = cam.read() 

    if ret: 
        # if video remains continue creating images 
        name = './video-frames/frame' + str(currentframe)+ '.jpg'
        print ('Creating...' + name) 

        # write extracted images 
        cv2.imwrite(name, frame) 

        #Counter to show number of frames that are being created 
        currentframe += 1
    else: 
        break

# Release all space and windows once done 
cam.release() 
cv2.destroyAllWindows()

相关问题 更多 >

    热门问题