对于读取图片有时候会出现‘NoneType‘ object has no attribute ‘shape‘的问题

有时候读取图片会出现'NoneType' object has no attribute 'shape'的问题,原因就在于读取的图片位深是8。一般三通道的图片位深是24。位深为8的图也可以是彩色图。

找出文件夹中所有位深为8的图的方法:

import os
import cv2
import shutil
 
dirName = '/A/b'
# 将dirName路径下的所有文件路径全部存入all_path列表
all_path = []
for root, dirs, files in os.walk(dirName):
        for file in files:
            if "jpg" in file:
                    all_path.append(os.path.join(root, file))
all_path.sort()


bad = []
badpath = '/A/c'

for i in range(len(all_path)):
    org = all_path[i]
    # print(all_path[i].split('/')[-1])
    try:
        img = cv2.imread(org)
        ss = img.shape
    except:
        bad.append(all_path[i])
        shutil.move(all_path[i],badpath)
        continue

print('共有%s张坏图'%(len(bad)))
print(bad)
print('=========DONE=========')

位深为8的图可以被cv2读入(读入后img为None),但是此时不会报错。在下一行读取img.shape的时候就会出现'NoneType' object has no attribute 'shape'的错误。此时(正在debug)可以去看org指示的图片是哪张,把那张图删掉即可。

 

这个同时也可以找出 libpng warning: iCCP: known incorrect sRGB profile 出现这个问题的图。

你可能感兴趣的:(python,深度学习)