error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor‘ & ValueError: operands could

1. Error 1: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

error: OpenCV(4.8.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Error code snippet:

error                                     Traceback (most recent call last)
d:\CodeProject\37.帮助大家看代码\demo.ipynb 单元格 48 line 9
      6 image2 = cv2.imread('D:\CodeProject\37.帮助大家看代码\cropped_(0, 0, 121, 168)_obj365_val_000000105931.jpg')
      8 # 将图像转换为灰度图像
----> 9 gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
     10 gray_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
     12 # 计算图像的直方图

error: OpenCV(4.8.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Insert image description here
This error is caused by an empty input image (i.e. _src.empty()) in the cv2.cvtColor function in the image processing code. This usually means that OpenCV did not successfully load or read the specified image file. To solve this problem, you can consider the following steps:

  1. Check the file path: Make sure the path to the image file is correct and that the file actually exists in the specified location. You can use absolute or relative paths, but make sure the path is correct.
  2. Check the file format: Make sure the image file format is a format supported by OpenCV, such as JPEG, PNG, etc. Sometimes a file may be corrupted or use an unsupported format, which causes the read to fail.
  3. Check image loading: Before reading the image, you can add some code to check if the image loaded successfully. For example:
if image1 is None or image2 is None:
    print("无法加载图像文件。")
else:
    # 继续进行图像处理

This will help you determine whether it's an image loading issue or a subsequent processing step that's causing the problem.

  • Try a different image loading method: If none of the above fixes the problem, you can try a different image loading method, such as using an absolute path or trying to load a different image file to test.
  • Check OpenCV version: Sometimes, there may be some issues with a particular version of OpenCV. Try updating or downgrading your OpenCV version to see if that helps resolve the issue.
  • Make sure OpenCV is installed correctly: If you are using pip installed OpenCV, make sure it is installed correctly and there are no dependency issues. You can try reinstalling OpenCV, or check the installation log for more information.

I changed the file path a bit:

Insert image description here

No more errors and output results smoothly!

2. Error 2: ValueError: operands could not be broadcast together

The first code is:

import cv2
import numpy as np

# 读取两个灰度图像
image1 = cv2.imread('./cropped_(0, 0, 121, 168)_obj365_val_000000105931.jpg', cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread('./cropped_(0, 0, 135, 268)_obj365_val_000000433336.jpg', cv2.IMREAD_GRAYSCALE)

# 检查图像是否成功加载
if image1 is None or image2 is None:
    print("无法加载图像")
else:
    # 转换图像为 NumPy 数组
    array1 = np.array(image1)
    array2 = np.array(image2)

    # 计算曼哈顿距离
    manhattan_distance = np.sum(np.abs(array1 - array2))

    # 打印曼哈顿距离
    print("曼哈顿距离:", manhattan_distance)

An error was reported when running:

ValueError: operands could not be broadcast together with shapes (168,121) (268,135) 

Insert image description here
This error is caused by mismatched dimensions of the two images. Manhattan distance calculation requires that the dimensions of the two images must be the same. In your example, the two images are of different dimensions, so the Manhattan distance cannot be calculated directly.

To solve this problem, we need to make sure that the two images being compared have the same dimensions. You can resize or crop the images so that they have the same dimensions before calculating the Manhattan distance. Here is a sample code that demonstrates how to resize two images to the same size and calculate the Manhattan distance:

import cv2
import numpy as np

# 读取两个灰度图像
image1 = cv2.imread('image1.jpg', cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread('image2.jpg', cv2.IMREAD_GRAYSCALE)

# 检查图像是否成功加载
if image1 is None or image2 is None:
    print("无法加载图像")
else:
    # 调整图像的大小为相同尺寸
    if image1.shape != image2.shape:
        image1 = cv2.resize(image1, (image2.shape[1], image2.shape[0]))

    # 转换图像为 NumPy 数组
    array1 = np.array(image1)
    array2 = np.array(image2)

    # 计算曼哈顿距离
    manhattan_distance = np.sum(np.abs(array1 - array2))

    # 打印曼哈顿距离
    print("曼哈顿距离:", manhattan_distance)

In this example, we first check if the dimensions of both images are the same, and if they are different, we use the cv2.resize function to resize one of the images to the same size as the other image. We then convert the two images into NumPy arrays and calculate the Manhattan distance.

No more errors, normal output results:

曼哈顿距离: 3715237

Guess you like

Origin blog.csdn.net/wzk4869/article/details/132858099