1. 安装opencv库
pip install opencv-python # Win
pip3 -H install opencv-python # Ubuntu
2. 读取、显示、保存图片
import cv2 # 导入库
img = cv2.imread('1.png') # 读取
cv2.namedWindow('img', cv2.WINDOW_NORMAL) # 可以缩放的窗口
cv2.imshow('img', img) # 显示
cv2.waitKey(0) # 持续显示
cv2.destroyAllWindows() # 销毁窗口
cv2.imwrite('1.jpg', img) # 保存
p.s
# 读取灰度图
img = cv2.imread('1.png', 0)
# 控制显示时间
cv2.waitKey(30) # 显示30ms
# 按Esc键退出显示(Esc的ASCII码为27)
while cv2.waitKey(0) != 27:
cv2.imshow('img', img)
3. 相机、视频的开关、读取
# 打开摄像头
cap = cv2.VideoCapture(0) # 电脑的第一个摄像头
while True:
ret, frame = cap.read() # frame即为摄像头读取的帧
cv2.imshow('frame', frame)
if cv2.waitKey(30) == 27:
break
cap.release() # 释放cap对象
cv2.destroyAllWindows()
# 打开视频文件
cap = cv2.VideoCapture('1.avi') # 打开本地 1.avi 的视频文件
while cap.isOpened():
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(30) == 27:
break
cap.release()
cv2.destroyAllWindows()
# 保存摄像机拍摄的视频文件
cap = cv2.VideoCapture(0)
fourcc = cv.VideoWriter_fourcc(*'XVID') # 定义四位的编码解码器(four codec)
# 定义输出,参数列表:filename, codec, frame_rate, (width, height)
output = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if ret==True:
output.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(20) == 27:
break
else:
break
cap.release()
cv2.destroyAllWindows()
# 将连续帧(图像)转化为视频
import cv2
import glob
name_list = glob.glob('./frames/*.bmp')
img = cv2.imread(name_list[0])
h, w = img.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*'XVID')
output = cv2.VideoWriter('raw.avi', fourcc, 20.0, (w, h))
for name in name_list:
frame = cv2.imread(name)
output.write(frame)
output.release()
4. 绘制图形(线、圆、矩形、椭圆、多边形、文字)
# 涉及函数
cv2.line() # 直线
cv2.circle() # 圆
cv2.rectangle() # 矩形
cv2.ellipse() # 椭圆
cv2.polylines() # 多边形
cv2.putText() # 文字
# 以上函数的部分参数列表
img: 背景图
color: 颜色
thickness: 线宽
lineType: 线型
start_point, end_point: 起始点
e.g
# 定义背景为512x512的RGB类型白色图像
img = np.zeros((512, 512, 3), np.uint8)
# 起点(0,0), 终点(511,511), 颜色:蓝(BGR:255,0,0), 线宽:5px
cv2.line(img, (0,0), (511,511), (255,0,0), 5)
# 对角点(384,0)(511,511), 颜色蓝,线宽5
cv2.retangle(img, (384,0), (511,511), (255,0,0), 5)
# 圆心(447,63) 半径63 shift精度偏移位-1
cv2.circle(img, (447,63),63,(0,0,255),-1)
# 椭圆参数: img, center, axes, startAngle, endAngle, color, thickness=1, lineType=8, shift
cv2.ellipse(img, (256,256), (100,50), 0, 0, 180, 255, -1)
# 定义多边形定点坐标
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1, -1, 2))
# img, pts, isClosed, color
cv2.polylines(img, [pts], True, (0,255,255))
# 在图像上添加显示文字
font = cv.FONT_HERSHEY_SIMPLEX # 定义字体
# img, text, start_point, fontface, fontscale, color, thickness, lineType
cv2.putText(img, 'Learn OpenCV Python!', (10,500), font, 4, (255,255,0), 2, cv2.LINE_AA)
5. 鼠标事件
# Easy Demo 简单例子
# 鼠标回调函数 callback function
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBCLK: # left button double click 左键双击
cv2.circle(img, (x,y), 100, (255,0,0),-1)
img = np.zeros((512,512,3), n.uint8)
cv2.namedWindow('img')
cv2.setMouseCallback('img', draw_circle)
while True:
cv2.imshow('img', img)
if cv2.waitKey(30) == 27:
break
cv2.destroyAllWindows()
# Advanced Demo 进阶例子
drawing = False # 鼠标是否按下
mode = True # True: 画矩形, False: 画曲线(按‘m’键)
ix, iy = -1, -1 # 初始化
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, mode # 全局变量
if event == cv2.EVENT_LBUTTONDOWN: # left button down 按下左键
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE: # mouse move 鼠标移动
if drawing == True:
if mode == True:
cv2.retangle(img, (ix,iy), (x,y), (0,255,0), -1)
else:
cv2.circle(img, (x,y), 5, (0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP: # left button up 左键抬起
drawing = False
if mode == True:
cv2.retangle(img, (ix,iy), (x,y), (0,255,0),-1)
else:
cv2.circle(img, (x,y), 5, (0,0,255), -1)
img = np.zeros((512,512,3), n.uint8)
cv2.namedWindow('img')
cv2.setMouseCallback('img', draw_circle)
while True:
cv2.imshow('img', img)
if cv2.waitKey(30) == 27:
break
cv2.destroyAllWindows()
6. 滑动条(动态改变参数显示图片)
def nothing: # callback
pass
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('img')
# 创建滑动条: barName, winName, min, max, callback
cv2.createTrackbar('R', 'img', 0, 255, nothing)
switch = '0:OFF \n1:ON'
cv2.createTrackbar(switch, 'img', 0, 1, nothing)
while True:
cv2.imshow('img', img)
if cv2.waitKey(30) == 27:
break
r = cv2.getTrackbarPos('R', 'img')
s = cv2.getTrackbarPos(switch, 'img')
if s==0:
img[:] = 0
else:
img[:] = [0,0,r]
cv2.destroyAllWindows()