Python 中的 OpenCV 库(Open Source Computer Vision Library)
OpenCV(Open Source Computer Vision Library) 是一个开源的计算机视觉库,支持 图像处理、视频分析、目标检测、机器学习 等任务。在 Python 中,它以 cv2
模块形式使用。
1. 安装 OpenCV
pip install opencv-python
如需使用包含 GUI 功能的版本(例如 imshow
),推荐安装完整版本:
pip install opencv-python-headless # 无 GUI 支持(用于服务器)
2. 基本使用示例
读取图像
import cv2
img = cv2.imread('image.jpg') # 默认按 BGR 加载
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
保存图像
cv2.imwrite('output.jpg', img)
3. 图像处理常用操作
灰度图转换
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
缩放图像
resized = cv2.resize(img, (100, 100))
图像翻转
flipped = cv2.flip(img, 1) # 0: 上下翻转;1: 左右翻转
4. 绘图函数
cv2.line(img, (0, 0), (100, 100), (0, 255, 0), 2)
cv2.rectangle(img, (10, 10), (200, 200), (255, 0, 0), 3)
cv2.circle(img, (100, 100), 50, (0, 0, 255), -1)
cv2.putText(img, 'OpenCV', (10, 300), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
5. 图像滤波
高斯模糊
blur = cv2.GaussianBlur(img, (5, 5), 0)
边缘检测(Canny)
edges = cv2.Canny(img, 100, 200)
6. 图像阈值处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
7. 图像轮廓检测
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
8. 摄像头操作
cap = cv2.VideoCapture(0) # 0 表示默认摄像头
while True:
ret, frame = cap.read()
cv2.imshow('Video', frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
9. 视频读写
读取视频
cap = cv2.VideoCapture('video.mp4')
保存视频
out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), 20.0, (640,480))
10. 人脸识别示例(基于 Haar 特征)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
11. 图像通道处理
分离通道
b, g, r = cv2.split(img)
合并通道
merged = cv2.merge([b, g, r])
12. 常见颜色空间转换
操作 | 代码 |
---|---|
BGR → 灰度 | cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
BGR → RGB | cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
BGR → HSV | cv2.cvtColor(img, cv2.COLOR_BGR2HSV) |
13. 与 NumPy 配合
OpenCV 中图像以 NumPy 数组的形式存储,可直接使用 NumPy 操作:
import numpy as np
img[100:200, 100:200] = [0, 255, 0] # 将区域变成绿色
mask = img[:, :, 0] > 100 # 按蓝色通道做掩码
14. 与 Matplotlib 显示图像
import matplotlib.pyplot as plt
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.axis('off')
plt.show()
15. OpenCV 常用函数速查表
功能 | 函数名 |
---|---|
读取图像 | cv2.imread() |
显示图像 | cv2.imshow() |
保存图像 | cv2.imwrite() |
改变尺寸 | cv2.resize() |
转颜色空间 | cv2.cvtColor() |
图像模糊 | cv2.GaussianBlur() |
边缘检测 | cv2.Canny() |
轮廓查找 | cv2.findContours() |
画图/写文字 | cv2.line() , cv2.putText() |
摄像头读取 | cv2.VideoCapture() |
视频保存 | cv2.VideoWriter() |
16. 总结
特性 | 优势 |
---|---|
跨平台支持 | 支持 Windows、Linux、macOS |
功能强大 | 图像/视频/机器学习/视觉全支持 |
与 NumPy 集成 | 图像直接作为数组操作 |
适用范围广 | 图像处理、目标检测、OCR、机器人视觉等 |
学习成本 | 简洁 API,适合快速上手 |
OpenCV 是图像与视频处理领域中最经典、最强大、最实用的工具之一,特别适合图像分析、CV 入门、原型开发、深度学习前处理等应用场景。配合 NumPy、Matplotlib、PIL、PyTorch 等库使用更为高效。