Contents
安装
1 2 3 |
pip install opencv-python pip install numpy |
获取图片
生成空白图片
1 2 3 |
black = np.zeros((300, 300, 3), np.uint8) black.fill(0) # 黑色 |
从图片文件读取
1 2 3 |
img = cv2.imread('1.jpg', cv2.IMREAD_COLOR) # 彩色 img = cv2.imread('1.jpg', 0) # 灰度 |
从视频文件读取
1 2 3 4 5 6 7 8 9 |
cap = cv2.VideoCapture('1.mp4') if not cap.isOpened(): print("video cannot open!\n") while True: ret, img = cap.read() if not ret: break |
从在线视频流读取
1 2 3 4 5 6 7 8 9 |
cap = cv2.VideoCapture('rtmp://****.*****/*****') if not cap.isOpened(): print("video cannot open!\n") while True: ret, img = cap.read() if not ret: break |
读取和调整图片大小
获取图片大小
1 2 |
h, w, _ = img.shape |
调整图片大小
1 2 |
img = cv2.resize(img, (500, 500)) |
常用绘图操作
二值化
1 2 3 |
ret, mask = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY) # 大于200的置为255 |
绘制文字
1 2 3 |
# 图片 文字 左上角坐标 字体 大小 颜色 粗细 cv2.putText(img, "txt", (x, y), 0, 2, (255, 255, 255), 3) |
绘制中文文本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from PIL import Image, ImageDraw, ImageFont def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20): if (isinstance(img, np.ndarray)): img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) # 字体 fontStyle = ImageFont.truetype( "MSYH.TTC", textSize, encoding="utf-8") # 绘制文本 draw.text((left, top), text, textColor, font=fontStyle) return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) image = cv2ImgAddText(image, '中文', 5, 5, (0, 255, 0), textSize=20) |
绘制矩形
1 2 3 4 5 |
x1, y1 = 20, 20 x2, y2 = 100, 100 # 图片 左上角坐标 右下角坐标 颜色 粗细 cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 255), 3) |
绘制直线
1 2 |
cv2.line(img, (x1, y1), (x2, y2), Scalar(33, 33, 133), 2) |
绘制多边形
1 2 3 |
poly = np.array([[150,50], [140,140], [200,170], [250,250], [150,50]], np.int32) cv2.polylines(img, [poly], True, (0,255,255), 3) |
颜色转换
RGB转为BGR
1 2 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
将图片的一部分复制到另一张图片
1 2 3 |
src = img[pt1y:pt2y, pt1x:pt2x] black[pt1y:pt2y, pt1x:pt2x] = src |
显示和保存图片
打开一个新窗口显示图片
1 2 3 4 5 6 7 8 9 10 |
cv2.imshow('image', img) # 在image窗口显示图片 cv2.imwrite('2.jpg', img) # 保存图片 # 全屏显示 window_name = 'result' cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN) cv2.moveWindow(window_name, 0, 0) cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) cv2.imshow("result", img) |
在notebook中显示图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import cv2 from PIL import Image import matplotlib.pyplot as plt import matplotlib %matplotlib inline img = cv2.imread('00001.png') fig, ax = plt.subplots(figsize=(16, 10)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ax.imshow(img) ax.set_axis_off() plt.show() |
按任意键继续
1 2 3 4 |
if cv2.waitKey(0) & 0xFF == ord('q'): #按下q键 #cap.release() # 释放视频 cv2.destroyAllWindows() |
参考
https://blog.csdn.net/what_lei/article/details/49159655
边缘检测
https://blog.csdn.net/weixin_43309755/article/details/89040894
PIL Image库的用法
https://www.cnblogs.com/lyrichu/p/9124504.html