【Python】cv2.error: OpenCV(4.8.0) :-1: error: (-5:Bad argument) in function ‘cvtColor‘ > Overload res

代码片段为:

# 将图片转换为灰度图
image1 = cv2.cvtColor(origin_iamge, cv2.COLOR_BGR2GRAY)
image2 = cv2.cvtColor(sp_image, cv2.COLOR_BGR2GRAY)
image3 = cv2.cvtColor(sp1_image, cv2.COLOR_BGR2GRAY)

mse_1 = mse(image1, image2)
mse_2 = mse(image1, image3)

ssim_1 = ssim(image1, image2)
ssim_2 = ssim(image1, image3)

我的代码出现了报错:

(PyTorch) D:\CodeProject>D:/Anaconda/envs/PyTorch/python.exe d:/CodeProject/2023_SZ_Cup/Problem_1/evaluate.py
Traceback (most recent call last):
  File "d:\CodeProject\2023_SZ_Cup\Problem_1\evaluate.py", line 20, in <module>
    image1 = cv2.cvtColor(origin_iamge, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.8.0) :-1: error: (-5:Bad argument) in function 'cvtColor'
> Overload resolution failed:
>  - src is not a numpy array, neither a scalar
>  - Expected Ptr<cv::UMat> for argument 'src'

【Python】cv2.error: OpenCV(4.8.0) :-1: error: (-5:Bad argument) in function ‘cvtColor‘ > Overload res_第1张图片

错误信息提示 cv2.error: (-5:Bad argument) in function ‘cvtColor’,这是因为在将图像从原始路径加载并转换为灰度图时,传递给 cv2.cvtColor 的参数不正确。

修改代码:

image1 = cv2.imread(origin_image_path, cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread(sp_image_path, cv2.IMREAD_GRAYSCALE)
image3 = cv2.imread(sp1_image_path, cv2.IMREAD_GRAYSCALE)

主要更改包括:

  1. 将图片路径作为参数传递给 cv2.imread 函数,以正确加载图片。
  2. 使用 cv2.IMREAD_GRAYSCALE 标志来确保图像被读取为灰度图像。

但是代码还是报错:

(PyTorch) D:\CodeProject>D:/Anaconda/envs/PyTorch/python.exe d:/CodeProject/2023_SZ_Cup/Problem_1/evaluate.py
[ WARN:0@0.328] global loadsave.cpp:248 cv::findDecoder imread_('./2023_SZ_Cup/datasets/B棰?Traceback (most recent call last):
  File "d:\CodeProject\2023_SZ_Cup\Problem_1\evaluate.py", line 21, in <module>
    mse_1 = mse(image1, image2)
  File "d:\CodeProject\2023_SZ_Cup\Problem_1\evaluate.py", line 7, in mse
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
AttributeError: 'NoneType' object has no attribute 'astype'

在这里插入图片描述

这个错误信息表明我们在读取图像时出现了问题,图片可能没有正确加载,导致后续的图像处理出错。

可以在读取图像后添加一些错误检查来确保图像是否成功加载。以下是修改后的代码,添加了错误检查和打印信息,以便更好地调试:

    # 读取图片并转换为灰度图
    image1 = cv2.imread(origin_image_path, cv2.IMREAD_GRAYSCALE)
    image2 = cv2.imread(sp_image_path, cv2.IMREAD_GRAYSCALE)
    image3 = cv2.imread(sp1_image_path, cv2.IMREAD_GRAYSCALE)

    if image1 is None or image2 is None or image3 is None:
        print("无法加载图像")
    else:
        mse_1 = mse(image1, image2)
        mse_2 = mse(image1, image3)

        ssim_1 = ssim(image1, image2)
        ssim_2 = ssim(image1, image3)

        print("-----调包-----")
        print('MSE:', mse_1)
        print('ssim:', ssim_1)

        print("-----算法-----")
        print('MSE:', mse_2)
        print('ssim:', ssim_2)

代码最后指出问题所在:

[ WARN:0@0.312] global loadsave.cpp:248 cv::findDecoder imread_('./2023_SZ_Cup/datasets/B棰?无法加载图像

修改名字即可!不再报错。

你可能感兴趣的:(Python3常用到的函数总结,错误或者警告类型解决办法总结,Python,OpenCV)