计算机视觉常用库安装与测试大全 (Python/C++)

计算机视觉开发离不开各种图像处理库。本文将详细介绍 Python 和 C++ 环境下主流视觉库的安装方法,并提供测试代码验证安装是否成功。


1. Python 环境安装

Python 生态中视觉库极其丰富,以下按使用频率排序介绍。

1.1 NumPy — 数值计算基础

几乎所有视觉库都依赖 NumPy,它是矩阵运算的基石。

1
pip install numpy

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np

print("NumPy Version:", np.__version__)

# 创建一个 3x3 单位矩阵
eye = np.eye(3)
print("3x3 单位矩阵:\n", eye)

# 随机矩阵运算
a = np.random.rand(3, 3)
b = np.random.rand(3, 3)
c = np.dot(a, b)
print("矩阵乘法结果:\n", c)

1.2 OpenCV — 计算机视觉核心库

OpenCV 是最流行的计算机视觉库,支持图像处理、视频分析、目标检测等。

1
2
3
4
5
6
7
8
# 基础版(推荐大多数用户)
pip install opencv-python

# 完整版(包含 contrib 模块,如 SIFT、SURF 等)
pip install opencv-contrib-python

# 带 GUI 支持的完整版(包含 imshow 等 GUI 功能)
pip install opencv-python-headless # 无 GUI 版本,适合服务器

版本选择建议

  • 本地开发:opencv-contrib-python(功能最全)
  • 服务器部署:opencv-python-headless(无 GUI 依赖,体积小)
  • 两者不要同时安装,会冲突

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import cv2
import numpy as np

print("OpenCV Version:", cv2.__version__)

# 创建一个 400x400 的黑色图像
img = np.zeros((400, 400, 3), dtype=np.uint8)

# 画一个蓝色矩形
cv2.rectangle(img, (50, 50), (350, 350), (255, 0, 0), -1)

# 画一个红色圆形
cv2.circle(img, (200, 200), 100, (0, 0, 255), 3)

# 添加文字
cv2.putText(img, "OpenCV Test", (80, 210), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)

# 显示图像(本地环境)
cv2.imshow("Test Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 保存图像(服务器环境可用)
cv2.imwrite("test_output.jpg", img)
print("图像已保存为 test_output.jpg")

1.3 Pillow (PIL Fork) — 图像处理利器

Pillow 是 PIL 的维护分支,适合图像格式转换、裁剪、滤镜等日常操作。

1
pip install Pillow

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from PIL import Image, ImageDraw, ImageFont
import numpy as np

print("Pillow Version:", Image.__version__)

# 创建一个 RGB 图像
img = Image.new("RGB", (400, 300), color=(30, 100, 200))

# 在图像上绘图
draw = ImageDraw.Draw(img)
draw.rectangle([50, 50, 350, 250], outline="white", width=3)
draw.text((100, 120), "Pillow Test", fill="white")

# 保存图像
img.save("pillow_test.png")
print("图像已保存为 pillow_test.png")

# 图像格式转换
img_jpg = img.convert("RGB")
img_jpg.save("pillow_test.jpg", "JPEG", quality=90)
print("已转换为 JPEG 格式")

1.4 scikit-image — 科学图像处理

scikit-image 基于 SciPy,提供高级图像处理算法(边缘检测、形态学操作等)。

1
pip install scikit-image

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import skimage
from skimage import data, filters, io
import matplotlib.pyplot as plt

print("scikit-image Version:", skimage.__version__)

# 使用内置测试图像
image = data.camera() # 内置的摄影师图像

# 边缘检测(Sobel 算子)
edges = filters.sobel(image)

# 显示结果
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(image, cmap="gray")
axes[0].set_title("原图")
axes[0].axis("off")
axes[1].imshow(edges, cmap="gray")
axes[1].set_title("Sobel 边缘检测")
axes[1].axis("off")
plt.tight_layout()
plt.savefig("skimage_test.png")
print("测试结果已保存为 skimage_test.png")

1.5 dlib — 人脸检测与特征点定位

dlib 在人脸检测、人脸关键点定位方面非常强大,常用于人脸识别项目。

1
2
3
# Windows 用户可能需要先安装 CMake
pip install cmake
pip install dlib

注意:dlib 安装可能较慢,因为它需要编译 C++ 代码。Windows 用户建议安装 Visual Studio Build Tools。

测试:

1
2
3
4
5
6
7
8
9
10
11
12
import dlib

print("dlib Version:", dlib.__version__)

# 测试人脸检测器
detector = dlib.get_frontal_face_detector()
print("人脸检测器加载成功")

# 测试形状预测器(需要下载模型文件)
# 下载地址: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
# predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
print("dlib 功能测试通过")

1.6 MediaPipe — 谷歌多媒体处理框架

MediaPipe 提供人脸检测、手势识别、姿态估计等预训练模型,开箱即用。

1
pip install mediapipe

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import mediapipe as mp

print("MediaPipe Version:", mp.__version__)

# 初始化人脸检测
mp_face_detection = mp.solutions.face_detection
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.5)

# 初始化手势识别
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(static_image_mode=True, max_num_hands=2)

# 初始化姿态估计
mp_pose = mp.solutions.pose
pose = mp_pose.Pose(static_image_mode=True)

print("MediaPipe 模型加载成功(人脸检测/手势识别/姿态估计)")

face_detection.close()
hands.close()
pose.close()

1.7 torchvision / torchaudio — PyTorch 视觉/音频工具

如果你使用 PyTorch 做深度学习,torchvision 提供数据集、模型和图像变换工具。

1
pip install torchvision torchaudio

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import torchvision
import torchvision.transforms as transforms
from torchvision import datasets

print("torchvision Version:", torchvision.__version__)

# 测试图像变换管道
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
print("图像变换管道创建成功")

# 加载预训练模型(首次会下载权重)
from torchvision.models import resnet18
model = resnet18(pretrained=False)
print("ResNet-18 模型加载成功")

1.8 imageio — 通用图像/视频读写

imageio 支持读写多种格式(PNG、JPEG、GIF、MP4 等),接口简洁。

1
pip install imageio

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import imageio
import numpy as np

print("imageio Version:", imageio.__version__)

# 创建并保存一张测试图像
img = np.random.randint(0, 255, (200, 200, 3), dtype=np.uint8)
imageio.imwrite("imageio_test.png", img)
print("随机图像已保存")

# 读取图像
img_read = imageio.imread("imageio_test.png")
print(f"读取图像尺寸: {img_read.shape}")

# 保存 GIF(多帧图像)
frames = [np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8) for _ in range(5)]
imageio.mimsave("imageio_test.gif", frames, duration=0.5)
print("GIF 已保存")

1.9 Matplotlib — 图像可视化

虽然 Matplotlib 主要是绑图库,但在视觉项目中常用于显示和对比图像。

1
pip install matplotlib

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import matplotlib.pyplot as plt
import numpy as np

print("Matplotlib Version:", plt.matplotlib.__version__)

# 创建子图对比
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

# 原图
img_original = np.random.rand(100, 100)
axes[0].imshow(img_original, cmap="gray")
axes[0].set_title("原图")
axes[0].axis("off")

# 水平翻转
img_flipped = np.fliplr(img_original)
axes[1].imshow(img_flipped, cmap="gray")
axes[1].set_title("水平翻转")
axes[1].axis("off")

# 旋转 90 度
img_rotated = np.rot90(img_original)
axes[2].imshow(img_rotated, cmap="gray")
axes[2].set_title("旋转 90°")
axes[2].axis("off")

plt.tight_layout()
plt.savefig("matplotlib_test.png", dpi=100)
print("对比图已保存为 matplotlib_test.png")

1.10 一键安装所有视觉库

如果你想一次性安装以上所有库:

1
pip install numpy opencv-contrib-python Pillow scikit-image dlib mediapipe torchvision imageio matplotlib

2. C++ 环境安装 (Linux Ubuntu)

在 C++ 环境下配置视觉库通常需要通过包管理器或源码编译。

2.1 OpenCV 安装

方法一:apt 安装(推荐,简单快捷)

1
2
sudo apt update
sudo apt install libopencv-dev python3-opencv

验证安装:

1
pkg-config --modversion opencv4

方法二:源码编译(可自定义模块)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 安装编译依赖
sudo apt install -y build-essential cmake git libgtk2.0-dev pkg-config \
libavcodec-dev libavformat-dev libswscale-dev libtbb2 libtbb-dev \
libjpeg-dev libpng-dev libtiff-dev libdc1394-dev

# 克隆源码
cd ~
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git

# 编译安装
cd opencv
mkdir build && cd build
cmake -D CMAKE_BUILD_TYPE=Release \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
-D BUILD_EXAMPLES=ON ..
make -j$(nproc)
sudo make install
sudo ldconfig

2.2 测试代码

创建 test_cv.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main() {
cout << "OpenCV Version: " << CV_VERSION << endl;

// 创建 400x400 黑色图像
Mat img = Mat::zeros(400, 400, CV_8UC3);

// 画绿色矩形
rectangle(img, Point(50, 50), Point(350, 350), Scalar(0, 255, 0), -1);

// 画红色圆形
circle(img, Point(200, 200), 100, Scalar(0, 0, 255), 3);

// 添加文字
putText(img, "OpenCV C++ Test", Point(70, 210),
FONT_HERSHEY_SIMPLEX, 0.8, Scalar(255, 255, 255), 2);

// 显示图像
imshow("Test Image", img);
waitKey(0);

return 0;
}

编译运行:

1
2
g++ test_cv.cpp -o test_cv `pkg-config --cflags --libs opencv4`
./test_cv

3. 常见问题排查

3.1 pip 安装超时

1
2
3
4
5
# 使用国内镜像源
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

# 永久设置镜像源
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

3.2 OpenCV 与 contrib 冲突

1
2
3
4
# 先卸载冲突的包
pip uninstall opencv-python opencv-contrib-python -y
# 再重新安装
pip install opencv-contrib-python

3.3 dlib 编译失败 (Windows)

1
2
3
4
5
6
7
# 安装 Visual Studio Build Tools
# 下载地址: https://visualstudio.microsoft.com/visual-cpp-build-tools/
# 安装时选择 "C++ 桌面开发"

# 然后重新安装
pip install cmake
pip install dlib

3.4 imshow 不显示窗口

1
2
3
# 安装 opencv-python 而不是 headless 版本
pip uninstall opencv-python-headless -y
pip install opencv-python

3.5 C++ 编译时找不到 OpenCV

1
2
3
# 检查 pkg-config 路径
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH
pkg-config --modversion opencv4

4. 各库适用场景速查

主要用途 特点
NumPy 矩阵运算、数值计算 所有视觉库的基础依赖
OpenCV 图像处理、视频分析、目标检测 功能最全,工业级标准
Pillow 图像格式转换、裁剪、滤镜 接口简单,适合日常处理
scikit-image 高级图像处理算法 科研导向,算法丰富
dlib 人脸检测、关键点定位 人脸识别项目首选
MediaPipe 人脸/手势/姿态估计 谷歌出品,预训练模型开箱即用
torchvision 深度学习数据集和模型 PyTorch 生态必备
imageio 图像/视频读写 格式支持广泛
Matplotlib 图像可视化、对比展示 科研论文绘图必备

分享
计算机视觉常用库安装与测试大全 (Python/C++)
https://asteriayx.github.io/2026/06/13/cv-libraries-setup/
作者
Asteriayx
发布于
2026年6月13日
许可协议