解决 error: (-215:Assertion failed) _src.empty() in function ‘cv::cvtColor‘

im, im_info = decode_image(im, im_info)   File "D:\PyCharm\Deployment\deploy_water\python\preprocess.py", line 34, in decode_image im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Solve the above error and cv2.imdecode(data, 1)=None

  I believe that everyone can also find such wrong posts on major platforms. Most of them talk about the following reasons. Summary:
1. There are Chinese characters in the image path, which causes problems in cv2 reading. The classmate wrote that there is no Chinese in the relative path . It should be noted that there is no Chinese in the relative path, and there is also no Chinese in the absolute path ! ! !
 Because the underlying code may convert it to an absolute path for you, so that the reader may pass in a relative path without Chinese, but it is implicitly converted to an absolute path, and the above error will also be reported. In short, there cannot be Chinese in the absolute path of the picture.

2. For the above Chinese path, you can read the image path as follows to make it compatible with the Chinese path.

  with open(im_file, 'rb') as f:
      im_read = f.read()
  data = np.frombuffer(im_read, dtype='uint8')
  im = cv2.imdecode(data, 1)  # BGR mode, but need RGB mode
  im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)

3. The author reports an error, there is no Chinese in the path, but the above error will still be reported ( the probability of this occurrence is low, but it may still happen )

insert image description here
                    There is no Chinese
insert image description here
                    image in the picture path and there is data

  Because when debugging the code, I found that the path is fine, and the data seems to be read in normally, which caused the author to be stuck for one and a half hours because of this problem, because there was a problem with the author's picture transmission, and the picture was damaged during transmission. So everyone must first check whether there is a problem with the picture read by cv2 before it can't be read.
insert image description here

Guess you like

Origin blog.csdn.net/qq_37700257/article/details/124756543