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

2024-09-24 22:22:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在代码中遇到问题的部分如下。在

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)

我收到以下错误

^{pr2}$

我知道imread()可能是空的,因为它试图读取的图像没有正确保存。我试图用保存为000001,000002,000003的3个图像来测试此代码。。。我不明白为什么保存在C:\imagez文件夹中的图像不能正常工作。我尝试保存3个新的图像,但仍然得到相同的错误。任何建议都太好了!在


Tags: 代码namein图像imageforifmain
1条回答
网友
1楼 · 发布于 2024-09-24 22:22:15

如果您阅读documentation on ^{},您可以看到它可能会失败—在这种情况下,它返回None(这就是Mat::data==NULL在python中的翻译):

The function imread loads an image from the specified file and returns it. 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 ).

如果您将None作为cv2.cvtColor(image, cv2.COLOR_BGR2RGB)的输入,那么在检查参数(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'并发现它是None时将引发一个错误:

修复:

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))

检查导致这些问题的路径的拼写是否正确-可能只是路径/文件名中的错误。在

相关问题 更多 >