Using Python opencv to realize the mutual conversion between video and picture
- 2021-07-10 20:24:50
- OfStack
Recently, we have to convert data sets frequently for experiments, so record 1.
1. Video to picture
That is, the video is parsed into a picture of 1 frame and 1 frame:
import cv2
vc=cv2.VideoCapture("/home/hqd/PycharmProjects/1/1/19.MOV")
c=1
if vc.isOpened():
rval,frame=vc.read()
else:
rval=False
while rval:
rval,frame=vc.read()
cv2.imwrite('/home/hqd/PycharmProjects/1/1/19/'+str(c)+'.jpg',frame)
c=c+1
cv2.waitKey(1)
vc.release()
2. Picture to video
That is, to convert pictures into video, the frame rate used here is 30 frames/second:
import cv2import os
fps = 30
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video_writer = cv2.VideoWriter(filename='./result.avi', fourcc=fourcc, fps=fps, frameSize=(1920, 1080))
for i in range(0,6000):
p = i
if os.path.exists('/home/hqd/PycharmProjects/1/qqqq/'+str(p)+'.jpg'): # Judge whether the picture exists or not
img = cv2.imread(filename='/home/hqd/PycharmProjects/1/qqqq/'+str(p)+'.jpg')
cv2.waitKey(100)
video_writer.write(img)
print(str(p) + '.jpg' + ' done!')
video_writer.release()
Summarize