简体   繁体   English

从 OpenCV-python 中的视频中保存感兴趣的帧

[英]Saving frame of interest from a video in OpenCV-python

The code below stores all frames from a video and then selects and stores frames of interest which in this case is a frame per 90 frames.下面的代码存储视频中的所有帧,然后选择并存储感兴趣的帧,在这种情况下是每 90 帧一帧。

import cv2
import numpy as np
import matplotlib.pyplot as plt 


vidcap = cv2.VideoCapture("video .wmv")

success,image = vidcap.read()
count = 0
success = True
frames = []
while success:
    frames.append(image)
    success,image = vidcap.read()
    count += 1
 
vidcap.release()

#print(len(frames))

interval = 90

selectframes = []
framenum = []  #frame number of the selected frame 

for i in range(0,len(frames),interval):
    selectframes.append(frames[i])
    framenum.append(i)

While the code works as intended, I just wanted to know if there is a better way of doing it.虽然代码按预期工作,但我只是想知道是否有更好的方法。

at the very least, you can do if count % 90 == 0: frames.append(image)至少, if count % 90 == 0: frames.append(image)

there is potential for optimization.有优化的潜力。 OpenCV's VideoCapture has not just a read() method but also the pair of grab() and retrieve() methods, which is precisely what read() does. OpenCV 的 VideoCapture 不仅有一个read()方法,而且还有一对grab()retrieve()方法,这正是 read() 所做的。 grab() only makes sure that the frame was acquired, retrieve() actually decodes it. grab() 只确保帧被获取,retrieve() 实际解码它。 this may or may not work on video files (depends on how well the backend/apiPreference implements it).这可能适用于视频文件,也可能不适用(取决于后端/apiPreference 实现它的程度)。 calling grab() without retrieve() would save the program the effort of actually decoding each frame.在没有retrieve() 的情况下调用grab() 将节省程序实际解码每一帧的工作量。

assuming grab() does less work than read(), you can try vidcap.grab() 90 times, once vidcap.retrieve(), and repeat.假设grab() 比read() 做的工作少,你可以尝试vidcap.grab() 90 次,一次vidcap.retrieve(),然后重复。

You can try this one你可以试试这个

import cv2
import os
count=1

vidcap = cv2.VideoCapture('video.wmv')
def getFrame(sec):
    vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
    hasFrames,image = vidcap.read()
    if hasFrames:
        dim = (512, 512)
        resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
        cv2.imwrite("images/"+str(count)+".png", resized)
    return hasFrames
sec = 0
frameRate = 90/1000

success = getFrame(sec)
while success:
    count = count + 1
    sec = sec + frameRate
    sec = round(sec, 2)
    success = getFrame(sec)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM