1. 图片处理操作
⭐ 图片尺寸获取
方法一:opencv
import cv2
img = cv2.imread('my_image.jpg',0)
height, width = img.shape[:2]
⭐ 图片resize
方法一:opencv
import cv2
frame = cv2.imread('./Pictures/python.png', cv2.IMREAD_UNCHANGED)
dim = (width, height)
resized = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
参考:https://www.cnblogs.com/lfri/p/10596530.html
⭐ 数组转化为图片
方法一:opencv,转化为 numpy 数组后通过 cv 显示
import numpy as np
import cv2 as cv
...
image = np.array(array) # array 为普通数组
cv2.imshow('test', image) # winname 显示图片的窗口名, mat 图片
cv2.waitKey() # 长显示
方法二:Pillow,转化为 Image 格式并显示
from PIL import Image
image = Image.fromarray(array)
image.show()
⭐ 图片保存
保存 cv2 打开的图片
import cv2
cv2.imwrite(output_path, img)
保存 Image 打开的图片
image.save(output_path)
⭐ 画矩形
cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
例如,填充一个绿色的实心矩形
cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), -1)
参数含义
参数 | 含义 |
---|---|
img | 图片 |
pt1 | 矩形的左上角 |
pt2 | 矩形的右下角 |
color | 矩形框的颜色,通常使用RGB |
thickness | 矩形框的线宽;负数或CV_FILLED表示矩形填充 |
lineType | 线的类型:8,4,CV_AA;4 连通 、8 连通、使用高斯滤波器画反锯齿线 |
shift |
⭐ 写文本
cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])
参数 | 含义 |
---|---|
img | 图片 |
text | 文本内容 |
org | 文字左下角在图片中的位置 |
font | 字体样式 |
fontFace | 字体格式,FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX |
lineType | 线的类型:8,4,CV_AA;4 连通 、8 连通、使用高斯滤波器画反锯齿线 |
fontScale | |
color | 字体颜色 |
thickness | 字体的线宽 |
lineType | 线的类型 |
bottomLeftOrigin |
2. 视频处理操作
⭐ 视频信息获取
import cv2
vcap = cv2.VideoCapture('video.avi')
if vcap.isOpened():
# 获取宽、高
video_width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
video_height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
# FourCC
video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))
# FPS
video_fps = vid.get(cv2.CAP_PROP_FPS)
⭐ 视频resize及保存
def resize_video(video_path, output_path, fx=0.5, fy=0.5):
vid = cv2.VideoCapture(video_path)
if not vid.isOpened():
raise IOError("Couldn't open webcam or video")
video_width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
video_height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))
video_fps = vid.get(cv2.CAP_PROP_FPS)
dim = (int(video_width * fx), int(video_height * fy))
new_video = cv2.VideoWriter(output_path, video_FourCC, video_fps, dim)
while vid.isOpened():
is_read, frame = vid.read()
try:
resized = cv2.resize(frame, dim, interpolation=cv2.INTER_NEAREST)
new_video.write(resized) # 保存视频最后一帧时会莫名报错,所以要使用try。
except:
break