OpenCV图像拼接出现CL_OUT_OF_RESOURCES错误求助
代码示例
import cv2 import os images =[] path = "Folder" for image in os.listdir(path): img = cv2.imread(os.path.join(path,image)) images.append(img) print("There are {} images".format(len(images))) print("Images are read") print("Creating stitcher") stitcher = cv2.Stitcher.create(mode=1) print("Stitcher is running") (status, stitched) = stitcher.stitch(images) cv2.imwrite("File.png", stitched)
报错信息
cv2.error: OpenCV(4.6.0)
D:\a\opencv-python\opencv-python\opencv\modules\core\src\ocl.cpp:5954:
error: (-220:Unknown error code -220) OpenCL error CL_OUT_OF_RESOURCES
(-5) during call: clEnqueueReadBuffer(q, handle=000001C39C840AE0,
CL_TRUE, 0, sz=1583382528, data=000001C4E6132080, 0, 0, 0) in function
'cv::ocl::OpenCLAllocator::map' OpenCV(4.6.0) Error: Unknown error
code -220 (OpenCL error CL_INVALID_COMMAND_QUEUE (-36) during call:
clEnqueueMapBuffer(handle=000001C3FB376060, sz=3341583) =>
0000000000000000) in cv::ocl::OpenCLAllocator::deallocate_, file
D:\a\opencv-python\opencv-python\opencv\modules\core\src\ocl.cpp, line
5761
问题描述
此前用OpenCV做图像拼接代码运行正常,今天运行类似代码时出现上述错误。之前读取147MB文件夹的图片无报错,这次70MB文件夹反而报错,是否需要清理内存?求解决方法。
解决方法
1. 禁用OpenCL加速
错误核心是OpenCL资源不足,直接禁用OpenCL可绕过GPU内存限制,强制OpenCV使用CPU处理:
# 在代码开头添加 cv2.ocl.setUseOpenCL(False)
2. 优化内存使用
文件夹总大小不代表内存占用,单图分辨率、数量才是关键。可以:
- 关闭其他占用大量内存的程序
- 过滤加载失败的图片,避免无效对象占用空间:
for image in os.listdir(path): img_path = os.path.join(path, image) img = cv2.imread(img_path) if img is not None: # 仅保留加载成功的图片 images.append(img)
3. 调整Stitcher模式
mode=1对应cv2.Stitcher_SCANS模式,内存需求较高,可切换到默认全景拼接模式:
stitcher = cv2.Stitcher.create(mode=0) # 使用cv2.Stitcher_PANORAMA模式
4. 重置运行环境
OpenCL可能存在资源泄漏,重启Python环境或系统可重置GPU资源状态,解决临时占用问题。
5. 降低图像分辨率
如果图像尺寸过大,先缩小再拼接可大幅减少内存压力:
for image in os.listdir(path): img_path = os.path.join(path, image) img = cv2.imread(img_path) if img is not None: # 缩小至原尺寸的1/2,可根据需求调整比例 img_resized = cv2.resize(img, (img.shape[1]//2, img.shape[0]//2)) images.append(img_resized)
内容的提问来源于stack exchange,提问作者64Bits

