OpenCV 图片和视频基本操作
这个主要是查 $API$,不涉及原理,如果用到新的功能,则更新此博客。
import cv2 img = cv2.imread('1.jpg') shape = img.shape # 返回图片的高度、宽度、深度组成的 tuple,高度和宽度指的是像素点个数 size = img.size # 获取图像的像素数目,返回高*宽*通道数(三通道的话顺序为 BGR) dataType = img.dtype # 图像的数据类型 res = cv2.resize(img, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_NEAREST) # 图片缩放到原来的二分之一,注意这里参数顺序为(w, h) cv2.namedWindow('input_image', cv2.WINDOW_AUTOSIZE) # 窗口大小不可调整 cv2.imshow('input_image', res) cv2.waitKey() # 窗口默认一直处于弹出窗状态, 可以加持续时间参数。 cv2.destroyAllWindows() # 按任意键盘关闭窗口
图片生成视频
import cv2 import numpy as np import pixels fps = 25 size = (900, 485) escapeTime = 0 pointSize = 2 thickness = 2 def ReadImg(file_name): img = cv2.imread(file_name) img = cv2.resize(img, size, interpolation=cv2.INTER_NEAREST) return img def AddTimeToImage(img, time): m, second = divmod(int(time), 60) hour, minute = divmod(m, 60) h_m_s = "{0}:{1}:{2}".format(str(hour).zfill(2), str(minute).zfill(2), str(second).zfill(2)) cv2.putText(img, # 图像 h_m_s, # 文字内容 (740, 450), # 坐标 cv2.FONT_HERSHEY_SIMPLEX, # 字体 1, # 大小 (0, 0, 0), # 颜色 1, # 字体厚度 cv2.LINE_AA) blankImg = cv2.cvtColor(np.zeros((485, 900), dtype=np.uint8) + 255, cv2.COLOR_GRAY2BGR) videoWriter = cv2.VideoWriter("video.avi", cv2.VideoWriter_fourcc('M','J','P','G'), fps, size) for i in range(1,3): img = ReadImg(("%s" + ".jpg") % str(i)) for j in range(50): escapeTime += 0.04 frame = img.copy() AddTimeToImage(frame, escapeTime) videoWriter.write(frame) count = 0 for item in pixels.datas: point = item[1::-1] pointColor= item[2:] cv2.circle(blankImg, point, pointSize, pointColor, thickness) count += 1 if count == 50: count = 0 escapeTime += 0.04 frame = blankImg.copy() AddTimeToImage(frame, escapeTime) videoWriter.write(frame)
OpenCV 读取 gif 文件:
gif = cv2.VideoCapture('3.gif') gif.read() while True: ret, frame = gif.read() if ret: frame = cv2.resize(frame, size) for i in range(2): videoWriter.write(frame) else: break
OpenCV 调用电脑摄像头录制视频:
def RecordVideo(duration=10): fps = 25 size = (640, 480) frameCount = duration * fps cap = cv2.VideoCapture(0) # 打开摄像头 videoWriter = cv2.VideoWriter("video.avi", cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, size) success, frame = cap.read() while success and frameCount > 0: videoWriter.write(frame) success, frame = cap.read() frameCount -= 1 cap.release()