Python OpenCV 完整指南
引言
OpenCV(开源计算机视觉库)是一个功能强大的库,广泛应用于图像处理和计算机视觉领域。它提供了数千种优化过的算法,涵盖了从基本的图像操作到高级机器学习的各种任务。本指南将带您深入了解如何使用 Python 和 OpenCV 进行图像处理和计算机视觉应用的开发。
1. 环境搭建
首先,您需要安装 Python 和 OpenCV。推荐使用 pip 进行安装:
bash
pip install opencv-python numpy
numpy 是 OpenCV 许多操作的基础,因此也需要安装。
2. 图像的读取、显示与保存
OpenCV 的核心在于处理图像。
2.1. 读取图像
使用 cv2.imread() 函数从文件中加载图像。
“`python
import cv2
读取图像,参数0表示以灰度图形式读取,1表示彩色图(默认),-1表示包含Alpha通道
img_color = cv2.imread(‘path/to/your/image.jpg’, 1)
img_gray = cv2.imread(‘path/to/your/image.jpg’, 0)
if img_color is None:
print(“Error: Could not read image.”)
exit()
“`
2.2. 显示图像
使用 cv2.imshow() 显示图像,cv2.waitKey() 等待按键,cv2.destroyAllWindows() 关闭所有窗口。
“`python
cv2.imshow(‘Color Image’, img_color)
cv2.imshow(‘Grayscale Image’, img_gray)
cv2.waitKey(0) # 0表示无限等待,其他数字表示等待毫秒数
cv2.destroyAllWindows()
“`
2.3. 保存图像
使用 cv2.imwrite() 将图像保存到文件。
python
cv2.imwrite('grayscale_output.jpg', img_gray)
print("Grayscale image saved successfully.")
3. 图像基本操作
图像在 OpenCV 中被视为 NumPy 数组,这使得我们可以方便地进行各种操作。
3.1. 访问像素
可以直接通过坐标访问像素值。
“`python
对于彩色图像 (B, G, R)
(b, g, r) = img_color[100, 100]
print(f”Pixel at (100, 100) – B:{b}, G:{g}, R:{r}”)
对于灰度图像
pixel_gray = img_gray[100, 100]
print(f”Pixel at (100, 100) – Gray:{pixel_gray}”)
修改像素值
img_color[100, 100] = [255, 0, 0] # 将该像素设为蓝色
“`
3.2. 图像属性
获取图像的尺寸、通道数、数据类型等。
python
print(f"Image shape (height, width, channels): {img_color.shape}")
print(f"Image size (total pixels): {img_color.size}")
print(f"Image data type: {img_color.dtype}")
3.3. 图像ROI(Region of Interest)
选择图像的某个区域进行操作。
python
roi = img_color[50:150, 120:220] # 截取从 (120, 50) 到 (220, 150) 的区域
cv2.imshow('ROI', roi)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.4. 图像通道分离与合并
彩色图像通常有蓝、绿、红三个通道。
“`python
b, g, r = cv2.split(img_color) # 分离通道
merged_img = cv2.merge([b, g, r]) # 合并通道
cv2.imshow(‘Blue Channel’, b)
cv2.imshow(‘Green Channel’, g)
cv2.imshow(‘Red Channel’, r)
cv2.waitKey(0)
cv2.destroyAllWindows()
“`
4. 图像处理
OpenCV 提供了丰富的图像处理功能。
4.1. 颜色空间转换
最常用的是 RGB 到灰度图 (GRAY) 和 HSV。
“`python
gray_img = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)
hsv_img = cv2.cvtColor(img_color, cv2.COLOR_BGR2HSV)
cv2.imshow(‘Gray’, gray_img)
cv2.imshow(‘HSV’, hsv_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
“`
4.2. 图像几何变换
包括缩放、平移、旋转、仿射变换和透视变换。
- 缩放:
cv2.resize()
python
resized_img = cv2.resize(img_color, (200, 300)) # 指定宽度和高度
# 或者按比例缩放
# resized_img = cv2.resize(img_color, None, fx=0.5, fy=0.5)
cv2.imshow('Resized', resized_img)
cv2.waitKey(0) - 平移: 需要创建平移矩阵。
python
import numpy as np
M = np.float32([[1, 0, 100], [0, 1, 50]]) # [1, 0, tx], [0, 1, ty]
rows, cols, _ = img_color.shape
shifted_img = cv2.warpAffine(img_color, M, (cols, rows))
cv2.imshow('Shifted', shifted_img)
cv2.waitKey(0) - 旋转:
cv2.getRotationMatrix2D()获取旋转矩阵,cv2.warpAffine()进行旋转。
python
center = (cols // 2, rows // 2)
M_rot = cv2.getRotationMatrix2D(center, 45, 1) # 旋转中心,角度,缩放比例
rotated_img = cv2.warpAffine(img_color, M_rot, (cols, rows))
cv2.imshow('Rotated', rotated_img)
cv2.waitKey(0)
4.3. 图像阈值处理
将图像分割成前景和背景。
python
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('Binary Threshold', thresh1)
cv2.waitKey(0)
4.4. 图像平滑/模糊
用于去噪。常见的有高斯模糊、均值模糊、中值模糊。
python
blurred_img = cv2.GaussianBlur(img_color, (5, 5), 0) # 5x5内核,sigmaX=0
cv2.imshow('Blurred', blurred_img)
cv2.waitKey(0)
4.5. 图像形态学操作
膨胀、腐蚀、开运算、闭运算等,常用于去噪、连通组件分析等。
python
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(img_gray, kernel, iterations=1) # 腐蚀
dilation = cv2.dilate(img_gray, kernel, iterations=1) # 膨胀
cv2.imshow('Erosion', erosion)
cv2.imshow('Dilation', dilation)
cv2.waitKey(0)
4.6. 边缘检测
Canny 边缘检测是经典且效果最好的方法之一。
python
edges = cv2.Canny(img_gray, 100, 200) # 低阈值,高阈值
cv2.imshow('Canny Edges', edges)
cv2.waitKey(0)
5. 特征检测与描述
OpenCV 提供了多种算法来检测图像中的关键点和描述符。
5.1. Harris 角点检测
“`python
dst = cv2.cornerHarris(img_gray, 2, 3, 0.04)
膨胀,使角点更明显
dst = cv2.dilate(dst, None)
img_color[dst > 0.01 * dst.max()] = [0, 0, 255] # 标记角点为红色
cv2.imshow(‘Harris Corners’, img_color)
cv2.waitKey(0)
“`
5.2. SIFT/SURF/ORB 等特征点
SIFT 和 SURF 是专利算法,在新版 OpenCV 中可能需要安装 opencv-contrib-python。ORB 是免费替代品。
“`python
ORB (Oriented FAST and Rotated BRIEF)
orb = cv2.ORB_create()
kp, des = orb.detectAndCompute(img_gray, None) # 关键点和描述符
img_kp = cv2.drawKeypoints(img_gray, kp, None, color=(0, 255, 0), flags=0)
cv2.imshow(‘ORB Keypoints’, img_kp)
cv2.waitKey(0)
“`
6. 对象检测与识别
6.1. Haar 级联分类器(人脸检测)
OpenCV 提供了预训练的 Haar 级联分类器用于人脸、眼睛等检测。
“`python
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + ‘haarcascade_frontalface_default.xml’)
faces = face_cascade.detectMultiScale(img_gray, 1.3, 5) # 缩放比例,最小邻居数
for (x, y, w, h) in faces:
cv2.rectangle(img_color, (x, y), (x+w, y+h), (255, 0, 0), 2) # 画出人脸矩形
cv2.imshow(‘Face Detection’, img_color)
cv2.waitKey(0)
“`
6.2. 模板匹配
在较大图像中搜索模板图像。
“`python
template = cv2.imread(‘path/to/your/template.jpg’, 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_color, pt, (pt[0] + w, pt[1] + h), (0, 255, 255), 2)
cv2.imshow(‘Template Matching’, img_color)
cv2.waitKey(0)
“`
7. 视频处理
OpenCV 同样支持视频的读取、处理和写入。
7.1. 读取视频
“`python
cap = cv2.VideoCapture(‘path/to/your/video.mp4’) # 或者 0 表示摄像头
if not cap.isOpened():
print(“Error: Could not open video stream or file.”)
exit()
while True:
ret, frame = cap.read() # ret 是布尔值,表示是否成功读取帧;frame 是图像
if not ret:
break
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Video Frame', gray_frame)
if cv2.waitKey(1) & 0xFF == ord('q'): # 按 'q' 键退出
break
cap.release() # 释放资源
cv2.destroyAllWindows()
“`
7.2. 保存视频
需要指定编码器。
“`python
fourcc = cv2.VideoWriter_fourcc(*’XVID’) # MPEG-4 编码器
out = cv2.VideoWriter(‘output.avi’, fourcc, 20.0, (640, 480)) # 文件名,编码器,帧率,帧尺寸
在循环中写入帧
out.write(frame)
out.release()
“`
8. 深度学习与 OpenCV
新版 OpenCV 集成了深度学习模块 (DNN),可以方便地加载和运行预训练模型。
8.1. 图像分类(例如使用 Inception)
“`python
示例:加载一个预训练的Caffe模型 (需要模型文件和配置文件)
net = cv2.dnn.readNetFromCaffe(‘deploy.prototxt’, ‘weights.caffemodel’)
# 准备图像 blob
blob = cv2.dnn.blobFromImage(img_color, 1.0, (224, 224), (104, 117, 123))
net.setInput(blob)
detections = net.forward()
“`
这部分内容通常更复杂,涉及模型的下载、输入预处理和输出后处理。
结论
Python OpenCV 是一个功能极其丰富的工具,从图像的加载、显示到复杂的特征检测、对象识别和深度学习推理,它都能提供高效的解决方案。本指南只是触及了其功能的冰山一角,鼓励您继续探索 OpenCV 的官方文档和各种教程,以解锁更多计算机视觉的奥秘。祝您在计算机视觉的道路上越走越远!
“`