简体   繁体   English

如何使 cv2.imread() 不为空?

[英]How to make cv2.imread() not empty?

The part of my code that I am having trouble on is the following.我遇到问题的代码部分如下。

if __name__ == '__main__':
    for n, image_file in enumerate(os.scandir(image_folder)):
        img = image_file
        fig, ax = plt.subplots(1)
#       mngr = plt.get_current_fig_manager()
#       mngr.window.setGeometry(250, 120, 1280, 1024)
        image = cv2.imread(image_file.path)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

I receive the following error我收到以下错误

 image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
    cv2.error: OpenCV(3.4.4) C:\projects\opencv-python\opencv\module\imgproc\src\color.cpp:181:error:(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

I understand that the imread() may be empty because the images it is trying to read are not correctly saved.我知道 imread() 可能是空的,因为它试图读取的图像没有正确保存。 I am trying to test this code with 3 images saved as 000001, 000002, 000003... I am confused on why the images that are saved in the folder in C:\\imagez are not working.我正在尝试使用另存为 000001、000002、000003 的 3 个图像来测试此代码......我对为什么保存在 C:\\imagez 文件夹中的图像不起作用感到困惑。 I have tried saving 3 new images and still get the same error.我尝试保存 3 个新图像,但仍然出现相同的错误。 Any advise would be great!任何建议都会很棒!

If you read the documentation on cv2.imread() you can see that it may fail - in that case it returns None (thats what Mat::data==NULL translates to in python):如果您阅读有关cv2.imread()文档,您会发现它可能会失败 - 在这种情况下,它返回None (这就是Mat::data==NULL在 python 中的转换):

The function imread loads an image from the specified file and returns it.函数 imread 从指定文件加载图像并返回它。 If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).如果无法读取图像(由于文件丢失、权限不当、格式不受支持或无效),则该函数返回一个空矩阵 ( Mat::data==NULL )。

If you feed None as input to cv2.cvtColor(image, cv2.COLOR_BGR2RGB) - it will raise an error on checking the argument (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' and finding it to be None :如果您将None作为输入提供给cv2.cvtColor(image, cv2.COLOR_BGR2RGB) - 它会在检查(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'的参数(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'并找到时(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'它是None

Fix:使固定:

if __name__ == '__main__':
    for n, image_file in enumerate(os.scandir(image_folder)):
        fig, ax = plt.subplots(1)
        image = cv2.imread(image_file.path)
        if image:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        else:
            print("Unable to load image at path {}".format(image_file))

Check the _exact_spelling of your paths that give you these problems - it may be simply a typo in your path/filename.检查给您带来这些问题的路径的 _exact_spelling - 这可能只是您的路径/文件名中的拼写错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM