2022-11-03 About the reasons and solutions for cv2.imread() returning None when reading images

This is a summary of how I found out why cv2.imread() returns None when reading images. I hope it will be helpful to everyone.

1. Specific questions and reasons

Because I wanted to use my own data to train the yolo model, I had to collect data, so I crawled a certain number of pictures from the Baidu Gallery, but when training the yolo model, cv2.imread() could not be read. Picture, the return result is None.

2. Causes and solutions

1) Baidu solution.
There is no doubt that when you encounter a problem, you have to search for information on the Internet to see if the same situation has occurred before and the related solutions. The online solutions are basically as follows: ① The path of the image
contains Chinese characters and cannot be read. cv2.imread() for taking pictures
does not support Chinese paths, so if there is a Chinese path and you do not plan to change the path name, you should read it according to the following method

import numpy as np
import cv2
img=cv2.imdecode(np.fromfile(imgpath, dtype=np.uint8), cv2.IMREAD_COLOR)

② Absolute path and relative path.
There is no doubt that this needs to be checked and verified repeatedly. There is no other way. Hahaha
2) Ask a friend for a
solution. Of course, after going through Baidu, I still didn’t solve this problem, so I asked again. Friends who work in related fields want to discuss some experience.
Needless to say, my friend did not solve this problem, but he gave me another method. The code is as follows:

from PIL import Image
import numpy as np
I = Image.open(imgpath)
I.show()
a = np.array(I)

At the same time, he also gave me an explanation, as shown in the picture, which may be the correct solution to the problem.
Insert image description here
3) Continue to search for the correct solution.
The suffix name of the picture you see may not be the real format of the picture , so I started Baidu. How to check the real format of the picture? Format, the method is as follows:
① Use drawing software to open the test picture
Insert image description here
② Select Save As to see the original format of the picture
Insert image description here
Oh, it is a .gif format picture, so when we read it with cv2.imread(), a return will appear In the case of None, at this point, the problem is solved hahaha

Of course, if we need to use this image later, we only need to transfer it. If we don’t need it, it’s okay to delete it directly hahaha

Reference links:
【1】Link: link
【2】Link: link

Guess you like

Origin blog.csdn.net/LJ1120142576/article/details/127676051