cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182

戴品
2023-12-01

调用OpenCV模块的cvtColor处理图片:

img_rgb = r'G:\手机照片2022\IMG_122440.jpg'
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

发生了报错,报错内容为:

[ WARN:0@0.011] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('G:\手机照片2022\IMG_122440.jpg'): can't open/read file: check file path/integrity
Traceback (most recent call last):
  File "G:\Test39.py", line 26, in <module>
    control_to_sketch(image, to_image)
  File "G:Test39.py", line 10, in control_to_sketch
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

报错原因:第1行的警告其实有给出了答案,就是路径问题,不能打开或读取文件,需要改一下路径(can't open/read file: check file path/integrity)。
解决方法:

  • 方法1:把路径中涉及到中文的文件夹的名称改为非中文名称,如:
img_rgb = r'G:\mobile_photo_2022\IMG_122440.jpg'
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
  • 方法2:重新建一个英文名称的文件夹,将文件放到该文件夹中测试。
 类似资料: