Home > 语言编程 > [Python]使用OpenCV实现图像和视频转换操作

[Python]使用OpenCV实现图像和视频转换操作

将视频按FPS拆解成单张图片
使用cv2.VideoCapture
cv2.VideoCapture(video_path)
计算FPS使用,注意部分压缩视频FPS存在丢帧情况,需要进行跳帧处理
fps = int(vidcap.get(cv2.CAP_PROP_FPS))

def video_split():
  video_path = 'test/video/video_01.mp4'
  video_name = video_path[:-4]
  vidcap = cv2.VideoCapture(video_path)
  success,image = vidcap.read()
  fps = int(vidcap.get(cv2.CAP_PROP_FPS))
  count = 0
  while success:
    image = image_process(image)
    cv2.imwrite("%s/%d.jpg" % (video_name, count), image)
    #if count % fps == 0:
    #    cv2.imwrite("%s/%d.jpg" % (video_name, int(count / fps)), image)
    print('Process %dth seconds: ' % int(count / fps), success)
    success,image = vidcap.read()
    count += 1

将单张图片集合合并成视频
使用cv2.VideoWriter
fourcc = cv2.VideoWriter_fourcc(‘D’, ‘I’, ‘V’, ‘X’) #不同视频编码对应不同视频格式(例:’I’,’4′,’2′,’0′ 对应avi格式)
video = cv2.VideoWriter( file_path, fourcc, fps, size)

def video_combine():
    path = 'test/video/video_01/'#文件路径
    filelist = os.listdir(path) #获取该目录下的所有文件名
    filelist.sort(key=alphanum_key)
    fps = 6
    size = (580,420) #图片的分辨率片
    file_path = 'test/video/video_01_out.mp4'#导出路径
    fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') #不同视频编码对应不同视频格式(例:'I','4','2','0' 对应avi格式)
    video = cv2.VideoWriter( file_path, fourcc, fps, size)
 
    for item in filelist:
        if item.endswith('.png'):     #判断图片后缀是否是.png
            item = path + '/' + item 
            image = cv2.imread(item)  #使用opencv读取图像,直接返回numpy.ndarray 对象,通道顺序为BGR ,注意是BGR,通道值默认范围0-255。
            video.write(image)        #把图片写进视频
    video.release() #释放

现在编码用到了CV_FOURCC获取编码格式:
CV_FOURCC(‘P’, ‘I’, ‘M’, ‘1’) = MPEG-1 codec
CV_FOURCC(‘M’, ‘J’, ‘P’, ‘G’) = motion-jpeg codec
CV_FOURCC(‘M’, ‘P’, ‘4’, ‘2’) = MPEG-4.2 codec
CV_FOURCC(‘D’, ‘I’, ‘V’, ‘3’) = MPEG-4.3 codec
CV_FOURCC(‘D’, ‘I’, ‘V’, ‘X’) = MPEG-4 codec
CV_FOURCC(‘U’, ‘2’, ‘6’, ‘3’) = H263 codec
CV_FOURCC(‘I’, ‘2’, ‘6’, ‘3’) = H263I codec
CV_FOURCC(‘F’, ‘L’, ‘V’, ‘1’) = FLV1 codec

参考:
https://blog.csdn.net/errors_in_life/article/details/72809580
http://www.fjii.com/yw/2018/0919/182870.shtml

Categories: 语言编程 Tags: ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.