OpenCV
图像属性
- 三通道:BGR
- 图像shape:height、weight、channel
打开图像
- 创建窗口 namedWindow
- 设置窗口大小 resizeWindow
- 找到图像路径,打开 imread
- 显示 imshow
- 等待 waitKey
- 释放窗口 destroyAllWindows
python
"""
1. 创建窗口
2. 设置窗口大小
3. 找到图像路径,打开
4. 显示
5. 等待
6. 释放窗口
"""
import cv2
# 创建窗口
# 参数1 窗口名字
# 参数2 模式
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
# 设置窗口大小
cv2.resizeWindow('img', 800, 600)
# 打开/读取图像
img = cv2.imread('./snower.jpg')
# print(img.shape)
# h w c
# (360, 360, 3)
# 显示图像
cv2.imshow('img', img)
# 等待
# 参数 > 0 则会等待ms
key = cv2.waitKey(1000)
# print(key)
# -1
# 释放窗口
cv2.destroyAllWindows()
效果图

视频采集
视频本质:由一帧一帧间隔时间很短的图像构成
- 接收摄像头 VideoCapture
- 0:打开本地摄像头
- 1-3:外接摄像头
- 读取一帧一帧的图像 isOpened
python
"""
视频
本质:由一帧一帧间隔时间很短的图像构成
"""
import cv2
# 0 表示打开本地摄像头
# 1 2 3 外接摄像头
# 路径 播放视频
# 打开摄像头 视频采集
cap = cv2.VideoCapture(0)
while cap.isOpened():
# 读取一帧一帧的图像
retval, frame = cap.read()
if not retval:
print('can not read frame')
break
# imshow 会默认创建一个窗口
cv2.imshow('frame', frame)
key = cv2.waitKey(25)
if key == ord('z'):
break
cap.release()
cv2.destroyAllWindows()
效果图

绘制几何图形、文字
- 线 line
- 圆 circle
- 矩形 rectangle
- 多边形 polylines
- 文字 putText
python
"""
常见几何图形
点
线:起始点 + 终点
矩形:左上角的点 + 右下角的点
圆:圆心 + 半径
多边形
"""
import cv2
import numpy as np
bg_img = cv2.imread('./snower.jpg')
# 参数1 绘制的图
# 参数2 起始点
# 参数3 终点
# 参数4 颜色
# 参数5 线的大小
cv2.line(bg_img, (350, 50), (100, 100), color=(0, 0, 255), thickness=2)
# 矩形
cv2.rectangle(bg_img, (50, 50), (100, 100), color=(0, 255, 0), thickness=-1)
# 圆
cv2.circle(bg_img, (150, 150), 50, color=(255, 0, 255), thickness=2)
pts = np.array([(90, 150), (150, 200), (200, 300), (300, 80), (80, 30)])
# 多边形
cv2.polylines(bg_img, [pts], isClosed=False, color=(255, 255, 0), thickness=2)
# 绘制文字
# org 绘制文字的坐标
cv2.putText(bg_img,
text='hello world',
org=(20, 50),
fontFace=cv2.FONT_ITALIC,
fontScale=1.5,
color=(0, 255, 255),
thickness=2)
cv2.imshow('img', bg_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
效果图
