张芷铭的个人博客

OpenCV 是开源计算机视觉库,提供图像处理、特征检测、视频分析等功能,支持 C++、Python、Java。

安装

1
2
3
4
5
# 基础安装
pip install opencv-python

# 完整版(含视频处理、GUI)
pip install opencv-contrib-python

常用示例

 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 cv2

# 图像读取与灰度转换
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('gray_image.jpg', gray)

# ORB 特征检测
orb = cv2.ORB_create()
keypoints = orb.detect(gray, None)
img_keypoints = cv2.drawKeypoints(gray, keypoints, None, color=(0, 255, 0))

# Haar 人脸检测
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

# 视频读取
cap = cv2.VideoCapture('video.mp4')
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    cv2.imshow('Frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

CUDA 加速编译

从源码编译启用 GPU 加速:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 安装依赖
apt-get install build-essential cmake git pkg-config
apt-get install libjpeg-dev libtiff-dev libpng-dev
apt-get install libavcodec-dev libavformat-dev libswscale-dev
apt-get install libgtk-3-dev libatlas-base-dev gfortran
apt-get install python3-dev libcuda1-11-6 libnpp-dev nvidia-cuda-toolkit

# 编译
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 WITH_CUDA=ON \
      -D CUDA_ARCH_BIN=9.0 ..
make -j8 && make install && ldconfig

CUDA 架构对照

GPU架构Compute Capability
H800Hopper9.0
A100Ampere8.0
V100Volta7.0

验证 CUDA 支持

1
2
import cv2
print(cv2.getBuildInformation())  # 确认 WITH_CUDA=YES

参考资料

Comments