import urllib.request
url = 'http://www.pyimagesearch.com/wp-content/uploads/2015/01/google_logo.png'
resp = urllib.request.urlopen(url)
bytearr=bytearray(resp.read())
image = np.asarray(bytearr, dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('URL2Image',image)
cv2.waitKey()
img = cv2.imread('0122.jpg')
# '.jpg'表示把当前图片img按照jpg格式编码,按照不同格式编码的结果不一样
img_encode = cv2.imencode('.jpg', img)[1]
data_encode = np.array(img_encode)
str_encode = data_encode.tobytes()
VideoCapture()
VideoCapture() 是用于从视频文件、图片序列、摄像头捕获视频的类
cap = cv2.VideoCapture( *args, **kwargs)
"""输出参数
(1) 输入视频路径 (str)
cv2.VideoCapture('D:/123.mp4')
(2) 输入摄像头id
cv2.VideoCapture(0)
cap.read()
cap.release()
cap.get()
cap.set()
cap.open()
cap.grab()
cap.isOpened()
cap.getBackendName()
cap.getExceptionMode()
fps = cap.get(cv2.CAP_PROP_FPS) # 获取视频fps
frame_all = cap.get(cv2.CAP_PROP_FRAME_COUNT) # 获取视频总帧数
rval, frame = cap.read() # 返回两个参数rval
ret是布尔值,读取帧是正确.返回True,文件结尾,返回值False。
frame就是每一帧的图像,是个三维矩阵 (720, 1280, 3)
# cv2.imshow() 显示
cap = cv2.VideoCapture('D:/123/MP4')
if cap.isOpened():
print('读取数据流成功')
else:
print('失败')
rate =cap.get(cv2.CV_CAP_PROP_FPS) # 获取帧率
# 循环读取每一帧
while True:
rval, frame = cap.read()
if rval:
cv2.imshow('frame', frame)
cv2.waitKey(10)
else:
cv2.waitKey(1000)
break
cap.release() # 释放视频流
cv2.destroyAllWindows() # 关闭所有窗口
cap.get()
cap.get() 参数
cv2.CAP_PROP_FPS 视频帧率
cv2.CAP_PROP_FRAME_COUNT 视频总的帧数
cv2.CAP_PROP_FRAME_WIDTH 帧的宽度
cv2.CAP_PROP_FRAME_HEIGHT 帧的高度
cv2.CAP_PROP_POS_MSEC 当前视频读取的时间戳
cv2.CAP_PROP_POS_FRAMES 基于0的索引将被解码/捕获下一帧
cv2.CAP_PROP_POS_AVI_RATIO
cv2.CAP_PROP_FOURCC 视频编码器格式
cv2.CAP_PROP_FORMAT byretrieve()返回的Mat对象的格式
cv2.CAP_PROP_MODE 指示当前捕获模式的后端特定值
cv2.CAP_PROP_BRIGHTNESS 视频图像的亮度(仅适用于相机)
cv2.CAP_PROP_CONTRAST 视频图像对比度(仅适用于相机)
cv2.CAP_PROP_SATURATION 视频图像的饱和度(仅适用于相机)
cv2.CAP_PROP_HUE 视频图像的色相(仅适用于相机)
cv2.CAP_PROP_GAIN 视频图像的增益(仅适用于相机)
cv2.CAP_PROP_EXPOSURE 视频的曝光(仅适用于相机)
cv2.CAP_PROP_CONVERT_RGB 视频图像是否已转换为RGB的布尔标志
cv2.CAP_PROP_WHITE_BALANCE_U 白平衡的U值
cv2.CAP_PROP_WHITE_BALANCE_V 白平衡的V值
cv2.CAP_PROP_RECTIFICATION 立体摄像机的整流标志
cv2.VideoWriter()
cv2.VideoWriter(filename, fourcc, fps, frameSize, isColor=None)
filename :文件路径
fourcc: 四个字符用来表示压缩帧的codec
fps: 视频帧率
frameSize 要保存的文件的画面尺寸 (w,h)
(img.shape(1),img.shape(0))
isColor:默认为True, 默认是彩色
#fourcc意为四字符代码(Four-Character Codes),顾名思义,该编码由四个字符组成,下面是VideoWriter_fourcc对象一些常用的参数,注意:字符顺序不能弄混
cv2.VideoWriter_fourcc('I', '4', '2', '0')
# 未压缩的YUV颜色编码,4:2:0色度子采样。兼容性好,但文件较大。文件扩展名.avi
cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),
MPEG-1编码类型,文件扩展名.avi。随机访问,灵活的帧率、可变的图像尺寸、定义了I-帧、P-帧和B-帧 、运动补偿可跨越多个帧 、半像素精度的运动向量 、量化矩阵、GOF结构 、slice结构 、技术细节、输入视频格式
cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
# MPEG-4编码类型,视频大小为平均值,MPEG4所需要的空间是MPEG1或M-JPEG的1/10,它对运动物体可以保证有良好的清晰度,间/时间/画质具有可调性
cv2.VideoWriter_fourcc('T', 'H', 'E', 'O')
# 音频压缩格式,有损压缩,类似于MP3等的音乐格式。,兼容性差,件扩展名.ogv
cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),
# FLV是FLASH VIDEO的简称,FLV流媒体格式是一种新的视频格式。由于它形成的文件极小、加载速度极快,使得网络观看视频文件成为可能,它的出现有效地解决了视频文件导入Flash后,使导出的SWF文件体积庞大,不能在网络上很好的使用等缺点。文件扩展名为.flv。
# 定义编解码器和创造对象
fourcc = cv2.VideoWriter_fourcc('I', '4', '2', '0')
videoWrite = cv2.VideoWriter('out.avi',fourcc,20.0,(640,480))
videoWrite.write(img)
# 在视频的每帧上面添加 文字
import cv2
old_videopath='/home/old.avi'
new_videopath='/home/new.avi'
video = cv2.VideoCapture(old_videopath)
# get size and fps of video
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = video.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')
outVideo = cv2.VideoWriter(new_videopath, fourcc, fps, (width, height))
while (True):
ret, frame = video.read()
if not ret:
print("... end")
break
cv2.putText(frame, 'This is a test', (int(width / 20), int(height / 8)),cv2.FONT_HERSHEY_SIMPLEX, 6, (0, 255, 0), 20, cv2.LINE_AA)
cv2.namedWindow('frame', 0)
cv2.imshow('frame', frame)
cv2.waitKey(2)
outVideo.write(frame)
cv2.destroyAllWindows() # 关闭所有窗口
video.release() # 释放视频流
outVideo.release() # 释放视频流
视频转图像(抽帧)
def extract_frames(video_path, save_dir, img_name, step=1):
:param video_path: 视频文件
:param save_dir: 保存的目录
:param png_name: 图片名称
:param step: 抽帧间隙 step>=1
:return:
video = cv2.VideoCapture()
if not video.open(str(video_path)):
print("can not open the video")
count = 0
while True:
_, frame = video.read()
if frame is None:
break
if count % step == 0:
imgfile_path = os.path.join(str(save_dir), str(img_name) + '-' + '{:04d}.png'.format(count))
# '{:04d}.png' 四位编号以0补齐
cv2.imwrite(imgfile_path, frame)
count += 1
video.release()
return
video_path = Path('databases/video/123.avi')
save_path = Path('databases/image2')
png_name = 'imge'
extract_frames(video_path, save_path, png_name, 1)
图像转视频(合成)
import cv2
from pathlib import Path
def image2video(img_dir, savevideo_path, savevideo_name, startimg_path,
V_fourcc=cv2.VideoWriter_fourcc('I', '4', '2', '0'),
V_FPS=7):
:param img_dir: 图像目录
:param savevideo_path: video要保存位置
:param savevideo_name: video要保存名字
:param startimg_path: 起始图像
:param V_fourcc: 保存格式
:param V_FPS: 保存帧率
:return:
# res = [x for x in reslist if os.path.isfile(x) and os.path.splitext(x)[0] == '.jpg' or '.png'] # img_dir(str)
imgfile_list = [x for x in img_dir.iterdir() if x.is_file() and x.suffix == '.jpg' or '.png'] # img_dir(Path)
startimg = cv2.imread(startimg_path)
imgInfo = startimg.shape
size = (imgInfo[1], imgInfo[0]) # 注意size
videoWrite = cv2.VideoWriter(str(savevideo_path.joinpath(savevideo_name)), V_fourcc, V_FPS, size)
# 写入对象 1 file name 2 编码器 3 帧率 4 尺寸大小
for i, imgfile in enumerate(imgfile_list):
img = cv2.imread(str(imgfile)) # read img
videoWrite.write(img) # write img
print('end1')
return
img_dir = Path('./databases/image/99')
savevideo_path = Path('./databases/image/99')
startimg_path = Path('./databases/image/99_75.jpg')
savevideo_name = 'test.avi'
fourcc = cv2.VideoWriter_fourcc('I', '4', '2', '0')
image2video(img_dir, savevideo_path, savevideo_name, startimg_path, V_fourcc=fourcc, V_FPS=7)