Python+Opencv Implementation of Transforming Picture and Video

  • 2021-08-28 20:39:18
  • OfStack

1. Install the Opencv package


pip install opvencv-python

2. Implementation code:

Video to picture:


import cv2
cap=cv2.VideoCapture('E:/video/video-02.mp4') #  Get 1 Video opens cap
isOpened=cap.isOpened #  Determine whether to turn it on 
print(isOpened)
fps=cap.get(cv2.CAP_PROP_FPS)
print(fps)
#  Get Width 
width=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
#  Obtain height 
height=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
i=0
while(isOpened):
  #  Before saving 10 Frame 
  if i==10:
    break
  else:
    i+=1
  (flag,frame)=cap.read() #  Read every 1 Frame, 1 Zhang image flag  Indicates whether to read the results  frame Content 
  fileName='E:/video/image'+str(i)+'.jpg'
  print(fileName)
  # flag Indicates whether the picture was read successfully 
  if flag==True:
    #  Control quality 
    cv2.imwrite(fileName,frame,[cv2.IMWRITE_JPEG_QUALITY,100])
print('end!')

Save picture as video:


import os
import cv2
import numpy as np

path = 'E:/video/img'
filelist = os.listdir(path)
#fourcc = cv2.cv.CV_FOURCC('M','J','P','G') #opencv Version is 2
fourcc = cv2.VideoWriter_fourcc(*'XVID') #opencv Version is 3

fps = 5 #  Video per second 24 Frame 
size = (1920, 1080) #  The size of the picture that needs to be converted to video 
#  You can use the cv2.resize() Make modifications 

video = cv2.VideoWriter('E:/video/2.avi', fourcc, fps, size)
#  Video is saved in the current directory 

for item in filelist:
  if item.endswith('.jpg'):
    #  Find all the suffixes in the path named .png You can replace the file with .jpg Or other 
    item = path + item
    img = cv2.imread(item)
    video.write(img)
video.release()
cv2.destroyAllWindows()

The above is Python + Opencv to achieve the picture, video, the details of the example, more information about python picture, video, please pay attention to other related articles on this site!


Related articles: