欢迎单击如下公众号“计算机视觉之光”,关注我们。
95 OpenCV与其他计算机视觉库的对比
计算机视觉技术在各个领域的广泛应用,使得开发者在选择工具时面临多种选择。OpenCV是其中最受欢迎的库之一,但它并不是唯一的选择。本节将对比OpenCV与其他常用的库,如TensorFlow、Keras、PyTorch和Scikit-Image,介绍各自的功能、适用场景,并通过具体例题展示它们的使用。
OpenCV概述
OpenCV(Open Source Computer Vision Library)是一个开源计算机视觉和机器学习软件库。它提供了数百个计算机视觉算法,支持多种编程语言(如C++、Python、Java等)和平台(如Windows、Linux、MacOS、Android等)。
主要功能:
图像处理:滤波、边缘检测、形态学操作等。 特征检测与匹配:SIFT、SURF、ORB等。 机器学习:支持向量机(SVM)、k-近邻算法(k-NN)等。 视频分析:对象跟踪、运动检测等。 3D重建:立体匹配、SfM等。
函数示例:
import cv2
# 读取图像
image = cv2.imread('example.jpg')
# 灰度转换
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray_image, 100, 200)
# 显示图像
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
![]()
![]()
TensorFlow与KerasTensorFlow是一个开源的机器学习框架,广泛用于深度学习模型的构建和训练。Keras是TensorFlow的高级API,提供了更简洁的接口,方便快速构建和训练神经网络。
适用场景:
深度学习模型的构建和训练 需要大规模数据和高性能计算的应用 集成TensorFlow的预训练模型
主要功能:
多种神经网络层和模型构建方法 自动微分和优化器 数据预处理和增强 模型评估和可视化
函数示例:
import tensorflow as tf
from tensorflow.keras import layers
# 构建简单的CNN模型
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 模型概览
model.summary()
输出结果:
C:\ProgramData\anaconda3\Lib\site-packages\keras\src\layers\convolutional\base_conv.py:107: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
super().__init__(activity_regularizer=activity_regularizer, **kwargs)
Model: "sequential"
┌─────────────────────────────────┬────────────────────────┬───────────────┐
│ Layer (type) │ Output Shape │ Param # │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d (Conv2D) │ (None, 26, 26, 32) │ 320 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ max_pooling2d (MaxPooling2D) │ (None, 13, 13, 32) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d_1 (Conv2D) │ (None, 11, 11, 64) │ 18,496 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ max_pooling2d_1 (MaxPooling2D) │ (None, 5, 5, 64) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ flatten (Flatten) │ (None, 1600) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense (Dense) │ (None, 64) │ 102,464 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_1 (Dense) │ (None, 10) │ 650 │
└─────────────────────────────────┴────────────────────────┴───────────────┘
Total params: 121,930 (476.29 KB)
Trainable params: 121,930 (476.29 KB)
Non-trainable params: 0 (0.00 B)
2024-06-10 21:05:23.341964: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-06-10 21:05:27.448302: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-06-10 21:05:36.024825: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
这段输出包含了对构建的简单CNN模型的各层结构、参数数量以及模型总体概览的信息,以及一些关于 TensorFlow 运行环境的信息和一些建议。
模型结构及参数数量:
一个 Conv2D
层,输出形状为 (None, 26, 26, 32),参数数量为 320。 一个 MaxPooling2D
层,输出形状为 (None, 13, 13, 32)。 一个 Conv2D
层,输出形状为 (None, 11, 11, 64),参数数量为 18,496。 一个 MaxPooling2D
层,输出形状为 (None, 5, 5, 64)。 一个 Flatten
层,输出形状为 (None, 1600)。 一个 Dense
层,输出形状为 (None, 64),参数数量为 102,464。 一个 Dense
层,输出形状为 (None, 10),参数数量为 650。 模型共包含了以下几层: 总参数数量为 121,930 (476.29 KB)。 可训练参数数量也是 121,930,非可训练参数数量为 0。
运行环境信息: TensorFlow 提出了一些建议,建议在使用 Sequential 模型时,最好不要将 input_shape
或 input_dim
参数传递给某一层,而是优先使用 Input(shape)
对象作为模型中的第一层。 还提供了有关 oneDNN 自定义操作的一些信息,提示可能会因为不同计算顺序而产生轻微不同的数值结果。如果想要关闭这些信息,可以设置环境变量 TF_ENABLE_ONEDNN_OPTS=0
。 最后,指出了该 TensorFlow 二进制文件已经优化,可使用可用的CPU指令进行性能关键操作。如果需要启用 AVX2 FMA 等指令,可以使用合适的编译器标志重新构建 TensorFlow。
综上,这段输出提供了关于构建模型、模型结构、参数数量以及 TensorFlow 运行环境的一些重要信息。
PyTorch
PyTorch是另一个流行的深度学习框架,特别受到研究人员和学术界的青睐。PyTorch以其动态计算图和易用性著称。
适用场景:
深度学习研究与开发 动态计算图和灵活的模型设计 实时计算和可视化
主要功能:
动态计算图 灵活的张量操作 神经网络模块 自动微分和优化器
函数示例:
import torch
import torch.nn as nn
import torch.optim as optim
# 定义简单的神经网络模型
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(12*12*64, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = torch.relu(self.conv1(x))
x = torch.relu(self.conv2(x))
x = torch.flatten(x, 1)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 实例化模型和优化器
model = SimpleCNN()
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
# 模型概览
print(model)
输出结果:
SimpleCNN(
(conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(fc1): Linear(in_features=9216, out_features=128, bias=True)
(fc2): Linear(in_features=128, out_features=10, bias=True)
)
Scikit-Image
Scikit-Image是一个基于Scipy的开源图像处理库,提供了丰富的图像处理功能,适用于学术研究和工程应用。
适用场景:
图像处理和分析 需要与Scipy和Scikit-Learn集成的应用 数据预处理和特征提取
主要功能:
图像滤波和变换 边缘检测和分割 特征检测和描述 图像复原和增强
函数示例:
from skimage import io, filters, feature
import matplotlib.pyplot as plt
# 读取图像
image = io.imread('apple.jpg', as_gray=True)
# 应用Sobel滤波器
edges = filters.sobel(image)
# 显示图像
plt.figure(figsize=(8, 4))
plt.subplot(121)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(122)
plt.title('Edges')
plt.imshow(edges, cmap='gray')
plt.show()
![]()
例题例题1:使用OpenCV进行边缘检测
任务:使用OpenCV实现图像的Canny边缘检测。
步骤:
读取图像并转换为灰度图。 应用高斯模糊。 使用Canny算法进行边缘检测。 显示结果图像。
import cv2
# 读取图像
image = cv2.imread('apple.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 应用高斯模糊
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
# Canny边缘检测
edges = cv2.Canny(blurred_image, 100, 200)
# 显示结果图像
cv2.imshow('Canny Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
![]()
例题2:使用TensorFlow进行图像分类
小结
本节对比了OpenCV与其他常用的计算机视觉库,包括TensorFlow、Keras、PyTorch和Scikit-Image。每个库都有其独特的优势和适用场景。OpenCV以其丰富的图像处理功能和高效的C++实现著称,是工程项目和实时应用的首选;TensorFlow和PyTorch则在深度学习研究和开发中占据重要地位;Scikit-Image适合图像处理和分析,特别是在与Scipy和Scikit-Learn集成时。通过具体的例题展示了各个库的基本用法,帮助大家更好地理解和应用这些工具。下一节将探讨计算机视觉职业路径与发展方向,为大家提供职业规划和发展建议。
这里简单介绍了一些基本知识点,更细致的内容请参考:
95 OpenCV与其他计算机视觉库的对比
计算机视觉技术在各个领域的广泛应用,使得开发者在选择工具时面临多种选择。OpenCV是其中最受欢迎的库之一,但它并不是唯一的选择。本节将对比OpenCV与其他常用的库,如TensorFlow、Keras、PyTorch和Scikit-Image,介绍各自的功能、适用场景,并通过具体例题展示它们的使用。
OpenCV概述
OpenCV(Open Source Computer Vision Library)是一个开源计算机视觉和机器学习软件库。它提供了数百个计算机视觉算法,支持多种编程语言(如C++、Python、Java等)和平台(如Windows、Linux、MacOS、Android等)。
主要功能:
图像处理:滤波、边缘检测、形态学操作等。 特征检测与匹配:SIFT、SURF、ORB等。 机器学习:支持向量机(SVM)、k-近邻算法(k-NN)等。 视频分析:对象跟踪、运动检测等。 3D重建:立体匹配、SfM等。
函数示例:
import cv2
# 读取图像
image = cv2.imread('example.jpg')
# 灰度转换
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray_image, 100, 200)
# 显示图像
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
TensorFlow是一个开源的机器学习框架,广泛用于深度学习模型的构建和训练。Keras是TensorFlow的高级API,提供了更简洁的接口,方便快速构建和训练神经网络。
适用场景:
深度学习模型的构建和训练 需要大规模数据和高性能计算的应用 集成TensorFlow的预训练模型
主要功能:
多种神经网络层和模型构建方法 自动微分和优化器 数据预处理和增强 模型评估和可视化
函数示例:
import tensorflow as tf
from tensorflow.keras import layers
# 构建简单的CNN模型
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 模型概览
model.summary()
输出结果:
C:\ProgramData\anaconda3\Lib\site-packages\keras\src\layers\convolutional\base_conv.py:107: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
super().__init__(activity_regularizer=activity_regularizer, **kwargs)
Model: "sequential"
┌─────────────────────────────────┬────────────────────────┬───────────────┐
│ Layer (type) │ Output Shape │ Param # │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d (Conv2D) │ (None, 26, 26, 32) │ 320 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ max_pooling2d (MaxPooling2D) │ (None, 13, 13, 32) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d_1 (Conv2D) │ (None, 11, 11, 64) │ 18,496 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ max_pooling2d_1 (MaxPooling2D) │ (None, 5, 5, 64) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ flatten (Flatten) │ (None, 1600) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense (Dense) │ (None, 64) │ 102,464 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_1 (Dense) │ (None, 10) │ 650 │
└─────────────────────────────────┴────────────────────────┴───────────────┘
Total params: 121,930 (476.29 KB)
Trainable params: 121,930 (476.29 KB)
Non-trainable params: 0 (0.00 B)
2024-06-10 21:05:23.341964: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-06-10 21:05:27.448302: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-06-10 21:05:36.024825: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
这段输出包含了对构建的简单CNN模型的各层结构、参数数量以及模型总体概览的信息,以及一些关于 TensorFlow 运行环境的信息和一些建议。
模型结构及参数数量:
一个 Conv2D
层,输出形状为 (None, 26, 26, 32),参数数量为 320。一个 MaxPooling2D
层,输出形状为 (None, 13, 13, 32)。一个 Conv2D
层,输出形状为 (None, 11, 11, 64),参数数量为 18,496。一个 MaxPooling2D
层,输出形状为 (None, 5, 5, 64)。一个 Flatten
层,输出形状为 (None, 1600)。一个 Dense
层,输出形状为 (None, 64),参数数量为 102,464。一个 Dense
层,输出形状为 (None, 10),参数数量为 650。模型共包含了以下几层: 总参数数量为 121,930 (476.29 KB)。 可训练参数数量也是 121,930,非可训练参数数量为 0。
TensorFlow 提出了一些建议,建议在使用 Sequential 模型时,最好不要将 input_shape
或input_dim
参数传递给某一层,而是优先使用Input(shape)
对象作为模型中的第一层。还提供了有关 oneDNN 自定义操作的一些信息,提示可能会因为不同计算顺序而产生轻微不同的数值结果。如果想要关闭这些信息,可以设置环境变量 TF_ENABLE_ONEDNN_OPTS=0
。最后,指出了该 TensorFlow 二进制文件已经优化,可使用可用的CPU指令进行性能关键操作。如果需要启用 AVX2 FMA 等指令,可以使用合适的编译器标志重新构建 TensorFlow。
综上,这段输出提供了关于构建模型、模型结构、参数数量以及 TensorFlow 运行环境的一些重要信息。
PyTorch
PyTorch是另一个流行的深度学习框架,特别受到研究人员和学术界的青睐。PyTorch以其动态计算图和易用性著称。
适用场景:
深度学习研究与开发 动态计算图和灵活的模型设计 实时计算和可视化
主要功能:
动态计算图 灵活的张量操作 神经网络模块 自动微分和优化器
函数示例:
import torch
import torch.nn as nn
import torch.optim as optim
# 定义简单的神经网络模型
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(12*12*64, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = torch.relu(self.conv1(x))
x = torch.relu(self.conv2(x))
x = torch.flatten(x, 1)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 实例化模型和优化器
model = SimpleCNN()
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
# 模型概览
print(model)
输出结果:
SimpleCNN(
(conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(fc1): Linear(in_features=9216, out_features=128, bias=True)
(fc2): Linear(in_features=128, out_features=10, bias=True)
)
Scikit-Image
Scikit-Image是一个基于Scipy的开源图像处理库,提供了丰富的图像处理功能,适用于学术研究和工程应用。
适用场景:
图像处理和分析 需要与Scipy和Scikit-Learn集成的应用 数据预处理和特征提取
主要功能:
图像滤波和变换 边缘检测和分割 特征检测和描述 图像复原和增强
函数示例:
from skimage import io, filters, feature
import matplotlib.pyplot as plt
# 读取图像
image = io.imread('apple.jpg', as_gray=True)
# 应用Sobel滤波器
edges = filters.sobel(image)
# 显示图像
plt.figure(figsize=(8, 4))
plt.subplot(121)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(122)
plt.title('Edges')
plt.imshow(edges, cmap='gray')
plt.show()
例题1:使用OpenCV进行边缘检测
任务:使用OpenCV实现图像的Canny边缘检测。
步骤:
读取图像并转换为灰度图。 应用高斯模糊。 使用Canny算法进行边缘检测。 显示结果图像。
import cv2
# 读取图像
image = cv2.imread('apple.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 应用高斯模糊
blurred_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
# Canny边缘检测
edges = cv2.Canny(blurred_image, 100, 200)
# 显示结果图像
cv2.imshow('Canny Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
例题2:使用TensorFlow进行图像分类
小结
本节对比了OpenCV与其他常用的计算机视觉库,包括TensorFlow、Keras、PyTorch和Scikit-Image。每个库都有其独特的优势和适用场景。OpenCV以其丰富的图像处理功能和高效的C++实现著称,是工程项目和实时应用的首选;TensorFlow和PyTorch则在深度学习研究和开发中占据重要地位;Scikit-Image适合图像处理和分析,特别是在与Scipy和Scikit-Learn集成时。通过具体的例题展示了各个库的基本用法,帮助大家更好地理解和应用这些工具。下一节将探讨计算机视觉职业路径与发展方向,为大家提供职业规划和发展建议。
这里简单介绍了一些基本知识点,更细致的内容请参考:
李立宗,OpenCV轻松入门(第2版),电子工业出版社,2023
李立宗,计算机视觉40例(从入门到深度学习:OpenCV-Python),电子工业出版社,2022
单击【阅读原文】参加OpenCV-Python课程学习。
单击【阅读原文】参加OpenCV-Python课程学习。
在本公众号【计算机视觉之光】回复关键字“叮叮当当”获取更多的Python学习资料。