import cv2
import argparse
parser=argparse.ArgumentParser('视频倒放')
parser.add_argument('videoPath',type=str,help='The path of video th input!')
parser.add_argument('flag',type=bool,help='True: save the reversed video; False: don\'t save the reversed video')
parser.add_argument('--outPath',type=str,help='The path to save the reversed video!',default=None)
args=parser.parse_args()
capture=cv2.VideoCapture(args.videoPath)
if capture.isOpened()==False:
print('Failed to open the video!')
capture.release()
exit(1)
frameW=capture.get(cv2.CAP_PROP_FRAME_WIDTH)
frameH=capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
frameN=capture.get(cv2.CAP_PROP_FRAME_COUNT)
frameIndex=frameN-1
writer=None
if args.flag:
fourcc=capture.get(cv2.CAP_PROP_FOURCC)
fps=capture.get(cv2.CAP_PROP_FPS)
outPath=args.outPath
if not(outPath):
inputPath=args.videoPath
index=inputPath.rindex('.')
outPath=inputPath[0:index]+'_reverse'+inputPath[index:]
writer=cv2.VideoWriter(outPath,int(fourcc),int(fps),(int(frameW),int(frameH)),True)
while capture.isOpened():
if frameIndex<0:
break
capture.set(cv2.CAP_PROP_POS_FRAMES,frameIndex)
flag,frame=capture.read()
if flag:
cv2.imshow('Current frame of video',frame)
if writer:
writer.write(frame)
key=cv2.waitKey(10)
if key==81 or key==113:
break
frameIndex-=1
else:
break
if writer:
writer.release()
capture.release()
cv2.destroyAllWindows()
调用方式
python VideoReverse.py inputVideo True outPath
python VideoReverse.py inputVideo False