OpenCV (cv2) 库
OpenCV (Open Source Computer Vision Library) 是一个开源的计算机视觉和机器学习软件库。以下是使用 cv2
模块的详细指南:
1. 安装 OpenCV
pip install opencv-python # 基础模块 # 或者 pip install opencv-contrib-python # 包含额外模块
2. 基本图像操作
读取和显示图像
import cv2 as cv
# 读取图像
img = cv.imread('image.jpg') # 返回NumPy数组
# 检查图像是否正确加载
if img is None:
print("无法加载图像")
else:
# 显示图像
cv.imshow('Image Window', img)
cv.waitKey(0) # 等待任意按键
cv.destroyAllWindows()
保存图像
cv.imwrite('output.jpg', img)
3. 图像处理基础
颜色空间转换
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # 转为灰度 hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) # 转为HSV
图像滤波
# 高斯模糊 blurred = cv.GaussianBlur(img, (5, 5), 0) # 边缘检测 edges = cv.Canny(img, 100, 200)
4. 视频处理
读取摄像头
cap = cv.VideoCapture(0) # 0表示默认摄像头 while True: ret, frame = cap.read() if not ret: break cv.imshow('Camera', frame) if cv.waitKey(1) == ord('q'): # 按q退出 break cap.release() cv.destroyAllWindows()
处理视频文件
cap = cv.VideoCapture('video.mp4')
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 在此处添加处理代码
processed = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow('Video', processed)
if cv.waitKey(25) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
5. 特征检测
人脸检测
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml') faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
角点检测
corners = cv.goodFeaturesToTrack(gray, 25, 0.01, 10) corners = np.int0(corners) for i in corners: x, y = i.ravel() cv.circle(img, (x, y), 3, (0, 0, 255), -1)
6. 实用技巧
图像缩放
resized = cv.resize(img, None, fx=0.5, fy=0.5, interpolation=cv.INTER_AREA)
绘制图形和文字
cv.rectangle(img, (50, 50), (200, 200), (0, 255, 0), 2) cv.circle(img, (300, 300), 50, (0, 0, 255), -1) cv.putText(img, 'OpenCV', (100, 100), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
获取图像属性
print(f"图像尺寸: {img.shape}") # (高度, 宽度, 通道数) print(f"像素总数: {img.size}") print(f"数据类型: {img.dtype}")
7. 高级功能
图像阈值处理
ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
轮廓检测
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) cv.drawContours(img, contours, -1, (0, 255, 0), 2)
8. 常见问题解决
-
图像路径问题:
-
使用绝对路径或确保相对路径正确
-
检查文件是否存在:
import os; print(os.path.exists('image.jpg'))
-
-
窗口不显示:
-
确保调用了
cv.waitKey()
-
在Jupyter中使用
matplotlib
显示
-
-
版本检查:
print(cv.__version__)
OpenCV 提供了丰富的计算机视觉功能,从基础的图像处理到高级的机器学习算法,是计算机视觉领域最常用的库之一。
NumPy 库
NumPy 是 Python 科学计算的基础库,提供了强大的多维数组对象和各种计算功能。
1. 安装 NumPy
基础安装
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
安装特定版本
pip install numpy==1.24.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
使用 conda 安装
conda install numpy
2. 验证安装
import numpy as np print(np.__version__) # 查看版本号 print(np.show_config()) # 查看编译配置
3. 基础使用示例
创建数组
import numpy as np # 从列表创建 a = np.array([1, 2, 3]) # 一维数组 b = np.array([[1, 2], [3, 4]]) # 二维数组 # 特殊数组 zeros = np.zeros((3, 4)) # 全0数组 ones = np.ones((2, 2)) # 全1数组 random = np.random.rand(3, 3) # 随机数组
数组运算
a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # 基本运算 print(a + b) # 加法 print(a * b) # 乘法(元素级) print(np.dot(a, b)) # 点积 # 广播机制 print(a + 5) # 数组与标量运算
4. 常用功能
数组索引和切片
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(arr[1, 2]) # 第2行第3列元素 print(arr[:, 1]) # 所有行的第2列 print(arr[1:3, 0:2]) # 子数组
数学函数
x = np.array([1, 2, 3]) print(np.sin(x)) # 三角函数 print(np.exp(x)) # 指数函数 print(np.log(x)) # 对数函数
统计计算
data = np.random.randn(100) # 100个随机数 print(np.mean(data)) # 平均值 print(np.std(data)) # 标准差 print(np.median(data)) # 中位数
5. 高级功能
矩阵运算
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(A @ B) # 矩阵乘法 print(np.linalg.inv(A)) # 矩阵求逆 print(np.linalg.det(A)) # 行列式
形状操作
arr = np.arange(12) # 0-11的一维数组 # 改变形状 mat = arr.reshape(3, 4) # 3行4列矩阵 flat = mat.flatten() # 展平为一维 # 转置 print(mat.T)
6. 性能优化技巧
向量化运算
# 不好的方式(使用循环) result = np.zeros(1000) for i in range(1000): result[i] = i * 2 # 好的方式(向量化) result = np.arange(1000) * 2
内存视图
big_array = np.random.rand(1000000) # 创建视图而非副本 view = big_array[::100] # 每100个元素取一个(不复制数据)
7. 常见问题解决
-
安装问题:
-
确保使用正确的Python环境
-
尝试升级pip:
python -m pip install --upgrade pip
-
-
性能问题:
-
使用NumPy内置函数而非Python循环
-
考虑使用
np.einsum
进行复杂运算
-
-
内存错误:
-
使用
np.save
/np.load
处理大型数组 -
考虑使用
dtype=np.float32
减少内存占用
-
8. 学习资源
NumPy 是Python数据科学生态系统的基石,掌握它将为学习Pandas、SciPy、scikit-learn等库打下坚实基础。
Matplotlib库
Matplotlib 是 Python 最流行的数据可视化库,以下是完整的安装和使用指南:
1. 安装 Matplotlib
基础安装
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
安装完整套件(推荐)
pip install matplotlib numpy pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
使用 conda 安装
conda install matplotlib
2. 验证安装
import matplotlib print(matplotlib.__version__) # 查看版本号
3. 基础使用示例
简单折线图
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 绘制图形
plt.figure(figsize=(8, 4)) # 设置图形大小
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.title('Sine Wave') # 标题
plt.xlabel('x') # x轴标签
plt.ylabel('sin(x)') # y轴标签
plt.legend() # 显示图例
plt.grid(True) # 显示网格
plt.show() # 显示图形
4. 常用图表类型
散点图
x = np.random.rand(50) y = np.random.rand(50) colors = np.random.rand(50) sizes = 1000 * np.random.rand(50) plt.scatter(x, y, c=colors, s=sizes, alpha=0.5) plt.colorbar() # 显示颜色条 plt.show()
柱状图
labels = ['A', 'B', 'C', 'D'] values = [15, 30, 45, 10] plt.bar(labels, values, color=['red', 'green', 'blue', 'yellow']) plt.show()
饼图
sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) # 突出第二部分 plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%') plt.axis('equal') # 保证是圆形 plt.show()
5. 多子图布局
使用 subplot
plt.figure(figsize=(10, 5)) # 第一个子图 plt.subplot(1, 2, 1) # 1行2列的第1个 plt.plot(x, np.sin(x), 'r-') # 第二个子图 plt.subplot(1, 2, 2) plt.plot(x, np.cos(x), 'b--') plt.tight_layout() # 自动调整子图间距 plt.show()
使用 subplots (推荐)
fig, axes = plt.subplots(2, 2, figsize=(10, 8)) # 2行2列 # 访问各个子图 axes[0, 0].plot(x, np.sin(x)) axes[0, 1].scatter(x, np.random.rand(100)) axes[1, 0].bar(labels, values) axes[1, 1].pie(sizes, labels=labels) plt.tight_layout() plt.show()
6. 高级功能
3D 图形
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) ax.plot_surface(X, Y, Z, cmap='viridis') plt.show()
自定义样式
plt.style.use('ggplot') # 使用ggplot风格 # 可用的内置样式 print(plt.style.available) # 自定义颜色和线型 plt.plot(x, y, color='#FF5733', linestyle='--', linewidth=2, marker='o', markersize=8)
7. 保存图形
plt.plot(x, y) plt.savefig('plot.png', dpi=300, bbox_inches='tight') # 保存为PNG plt.savefig('plot.pdf') # 保存为PDF
8. 常见问题解决
-
中文显示问题:
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
-
图形不显示:
-
确保最后调用了
plt.show()
-
在Jupyter中使用
%matplotlib inline
-
-
性能优化:
-
对于大数据集,使用
rasterized=True
-
考虑使用
plt.tight_layout()
自动调整布局
-
9. 学习资源
Matplotlib 提供了丰富的可视化功能,从简单的2D图表到复杂的3D可视化,是数据分析和科学研究的重要工具。