参考
我的配置环境
windows 11
python 3.9.10
cuda 12.0.1
RTX 3060
opencv 4.7.0
# 注意,安装 GPU 版的 openvc 之前需要把原本的 opencv 删除
配置过程
- 下载 预构建代码: opencv_contrib_cuda_4.7.0_win_amd64,并解压,得到两个文件夹。
- 将 下面路径 添加到 环境变量 path 中:
- 将 .pyd 文件添加到自己 python 环境下的 site-packages 中即可:可系统、可虚拟
- 然后你运行以下代码时会报错:
import cv2
# import cv2 as cv
print(f'OpenCV: {cv2.__version__} for python installed and working')
# ImportError: DLL load failed while importing cv2:找不到指定的模块。
解决方法:你可以添加以下三行:(需要根据自己的安装环境添加)
import os
# 使用os模块中的add_dll_directory函数
# 用于将指定路径添加到DLL搜索路径中,以便在程序运行时加载DLL文件
os.add_dll_directory('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v12.0\\bin')
os.add_dll_directory('E:\\opencv_contrib_cuda_4.7.0_win_amd64\\install\\x64\\vc17\\bin')
import cv2
# import cv2 as cv
print(f'OpenCV: {cv2.__version__} for python installed and working')
YES,这就成功了

rtsp GPU读取实例(注:这是我抄的,忘记抄谁的了)
import os
os.add_dll_directory('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v12.0\\bin')
os.add_dll_directory('E:\\opencv_contrib_cuda_4.7.0_win_amd64\\install\\x64\\vc17\\bin')
import cv2
# RTSP URL,修改成自己的URL
rtsp_url = "rtsp://127.0.0.1:8554/video"
# 使用GPU加速
cv2.cuda.setDevice(0)
# 创建VideoCapture对象
cap = cv2.VideoCapture(rtsp_url)
# 检查摄像头是否打开
if not cap.isOpened():
print("无法打开RTSP流")
else:
while True:
# 从RTSP流中读取一帧
ret, frame = cap.read()
if ret:
cv2.imshow('RTSP Stream', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
ok,完结,撒花,开始学习!