open-cv:从视频,动图,相机获取图片

cap = cv2.VideoCapture(‘文件名称’) 构建视频文件的cap实例。
cap.read()方法逐帧提取视频,每一帧为一幅图像
cap.read()方法返回的是一个二元组,下标0的元素值为True或False,如果为Flase表示读取文件完成。下标1的元素为图像对象,也是一个numpy数组类型的数据。read()方法读取是一帧一帧的。
cap.isOpened()用来检查cap实例是否已打开。
cap.release()释放实例。

import cv2
cap = cv2.VideoCapture('video_3.mp4')
while cap.isOpened():
    ret, img = cap.read()
    if ret is not True:
        print("读取完成,退出")
        break      
    #处理img
    cv2.imshow('vedio', img)
    
    #检查按键
    key = cv2.waitKey(20) & 0xff
    if  key == ord('q') or key == ord('Q') :
        break
        
print('cap.isOpened():',cap.isOpened())
cap.release()
print('cap.isOpened():',cap.isOpened())

cap.isOpened(): True
cap.isOpened(): False

2.从动态图像获取

import os
import time
import cv2 
def split_image(fn,path='.\\'):
    '''
    从gif中分离图片
    '''
    fn_full_path = path+fn
    cap = cv2.VideoCapture(fn_full_path)
    count_img = 0
    while True:
        flag,img = cap.read()
        if flag is not True:break
        cv2.imshow('img',img)
        print(img.shape())
        cv2.waitKey()
        cv2.imwrite(str(count_img)+'.jpg',img)
        count_img += 1
        print('count_img=',count_img)


img_fn = '1.gif'
split_image(img_fn)

3.

从相机获取图像:打开相机需要用相机的设备编号(数值型整数)作为入参传入VideoCapture(相机编号),比如cap = cv2.VideoCapture(0)构建编号为0的相机访问实例,第2台相机则传入1,以此类推,后续步骤的处理方法和读取视频文件一样。

4.

写入视频文件
写入视频文件需要创建VideoWriter对象,依次有四个参数
第一个文件名称 ;
第二个为编码方式,其中编码方式和文件名称后缀有对应关系
第三个参数为每秒写入的帧数,参考数值为25,符合人眼习惯
第四个参数是图像大小,int 类型
几种常用文件名称后缀和编码方式的对应关系:
avi–XVID
avi–MJPG
avi–mp4v
mp4–mp4v
编码方式需要创建VideoWriter_fourcc对象,下面给了两种方式创建MJPG类型编码:

fourcc=cv2.VideoWriter_fourcc('M','J','P','G')
fourcc=cv2.VideoWriter_fourcc(*'MJPG')

下面是图像大小的获取方式,可以通过cat.get(propld)方法,但是该方法获取的是float类型,需要转换为int类型再传入VideoWriter。

cap = cv2.VideoCapture(0)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) 
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = int(width)
height = int(height)

下面是一个创建XVID、MJPG、mp4v等3种编码方式视频文件的例子:

import cv2
 
#获取图像宽高
cap = cv2.VideoCapture(0)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) 
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = int(width)
height = int(height)
print(width,height)
 
#创建VideoWriter对象
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 25.0, (width,  height))
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out2 = cv2.VideoWriter('output2.avi', fourcc, 25.0, (width,  height))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out3 = cv2.VideoWriter('output3.mp4', fourcc, 25.0, (width,  height))

while cap.isOpened():   
    ret, img = cap.read()
    print(img.shape)
    if ret is not True:
        print("读取失败,退出")
        break      
    #处理img
    cv2.imshow('vedio', img)
    out.write(img)
    out2.write(img)
    out3.write(img)

    #检查按键
    key = cv2.waitKey(1) & 0xff
    if  key == ord('q') or key == ord('Q') :
        break
 
cap.release()
out.release()
out2.release() 
out3.release()

猜你喜欢

转载自blog.csdn.net/aqiangdeba/article/details/129750803
今日推荐