OpenCV基本操作
读取图像
img = cv2.imread(filename)
参数说明
返回值
表示图像的数组
显示图像
cv2.imshow(name, frame)
参数说明
返回值
无
保存图像
cv2.imwrite(filename, frame)
参数说明
返回值
无
打开视频流
cap = cv2.videoCapture(id)
打开视频资源,获取一个videoCapture对象,后续可通过读此对象得到图像画面
参数说明
返回值
videoCapture对象
从视频流中读取图像
ret, frame = cap.read()
参数说明
返回值
ret: 如果正确读取帧,ret为True,否则为False
frame:表示一帧图像的数组
颜色空间转换
img = cv2.cvtColor(frame, code)
参数说明
frame:传入图像
code:转换代码,如灰度变换cv2.COLOR_BGR2GRAY,hsv变换cv2.COLOR_BGR2HSV,这里的BGR是因为opencv默认按照蓝、绿、红进行排列
返回值
img:转换后的图像
使用示例:打开并显示摄像头画面
#!coding: utf-8
import cv2
import numpy as np
Key_Esc = 27
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
# 逐帧捕获
ret, frame = cap.read()
# 如果正确读取帧,ret为True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# 灰度变换
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 显示原图或灰度图
cv2.imshow('frame', np.rot90(cv2.resize(frame, (320, 240))))
# cv2.imshow('gray', np.rot90(cv2.resize(gray,(320,240))))
# 按Esc键退出,不加这一句可能无法正常显示图像
if cv2.waitKey(1) == Key_Esc:
break
# 完成所有操作后,释放捕获器
cap.release()
cv2.destroyAllWindows()
颜色查找
mask = cv2.inRange(frame, lowerb,upperb)
参数说明
frame:传入图像
lowerb:颜色区间下限
upperb:颜色区间上限
返回值
mask:黑白阈值图像(也被称为掩膜图像),和传入图像尺寸一致,在查找颜色区间内的区域会被设为白色,不在区间内的会被设为黑色
黑 | 灰 | 白 | 红 | 橙 | 黄 | 绿 | 青 | 蓝 | 紫 | |
---|---|---|---|---|---|---|---|---|---|---|
H | 0-180 | 0-180 | 0-180 | 0-10,156-180 | 11-25 | 26-34 | 35-77 | 78-99 | 100-124 | 125-155 |
S | 0-255 | 0-43 | 0-30 | 43-255 | 43-255 | 43-255 | 43-255 | 43-255 | 43-255 | 43-255 |
V | 0-46 | 47-220 | 221-255 | 46-255 | 46-255 | 46-255 | 46-255 | 46-255 | 46-255 | 46-255 |
轮廓检测
contours, hierarchy = cv2.findContours(mask,mode,method)
参数说明
mask:要检测的图像,黑白阈值图
mode:检测模式,cv2.RETR_TREE检测所有轮廓,所有轮廓建立一个等级树结构
method:检测方法,cv2.CHAIN_APPROX_SIMPLE仅保存轮廓的拐点信息
返回值
contours:轮廓中所包含的线段点集
hierarchy:轮廓之间的层级
计算轮廓面积
area = cv2.contourArea(cnt)
参数说明
返回值
area:轮廓面积
轮廓拟合
center,wh,angle = cv2.minAreaRect(cnt)
参数说明
返回值
拟合矩形的参数
center:矩形中心点坐标
wh:矩形宽和高
angle:矩形倾角(弧度制)
使用示例:基于opencv做颜色检测
#!coding: utf-8
import numpy as np
import cv2
Key_Esc = 27
cap = cv2.VideoCapture(0)
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
while True:
ret, frame = cap.read()
# hsv变换
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower_blue, upper_blue)
res = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(res) == 2:
# python3 写法
contours, hierarchy = res
elif len(res) == 3:
# python2 写法
_, contours, hierarchy = res
# 用黄色绘制出轮廓(BGR 0,255,255)
cv2.drawContours(frame, contours, -1, (0, 255, 255), thickness=2)
# 显示处理结果
cv2.imshow('detected', np.rot90(cv2.resize(frame, (320, 240))))
# cv2.imshow('mask', np.rot90(cv2.resize(mask,(320,240))) )
# 按q键退出,不加这一句可能无法正常显示图像
if cv2.waitKey(1) == Key_Esc:
break
cap.release()
cv2.destroyAllWindows()