原文链接:https://blog.xieqiaokang.com/posts/1153766715.html
图像
读、写、展示
img = cv2.imread(img_path)
cv2.imwrite(save_path, img)
cv2.imshow(name_of_window, img)
基础操作
img.shape # (rows, columns, channels)
img.size # (total number of pixels)
img.dtype # (datatype of image)
img2 = cv2.resize(img, (w,h), interpolation) # interpolation=cv2.INTER_CUBIC
画矩形框
import cv2
# color:(*,*,*)
# thickness:粗细(thickness=-1表示填充效果)
cv2.rectangle(img, (x,y), (x+w,y+h), color, thickness=3)
画圆
# r:半径
cv2.circle(img, (x,y), r, color, thickness)
绘制文字
# e.g. font = cv2.FONT_HERSHEY_COMPLEX
# thickness=-1表示填满
cv2.putText(img, 'text', (x,y), font, size, color, thickness)
Resize
cv2.resize(img, (w,h))
PIL.Image 和 OpenCV 图像格式转换
# PIL 转 OpenCV
img = Image.open('1.jpg')
img = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
# OpenCV 转 PIL
img = cv2.imread('1.jpg')
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
视频
写视频
import cv2
# 定义视频参数
fps = 30
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
writer = cv2.VideoWriter(video_name, fourcc, fps, (w,h))
# 写入视频帧
for ...
writer.write(img)
...
# 释放
writer.release()