最近在使用imgnet的过程中发现老是出现报错的问题,最开始以为是代码的问题,后来不断的查找,发现出在数据集上面,imgnet数据集的图片来自网络,大部分图片都是RGB,但是还有一些是灰度图甚至四维图,当这些数据被导入进深度学习模型时,会导致模型报错。所以就需要将这种图片先筛选出去,我选择直接删除。具体实现如下:
img_dir = '../../data/Imgnet2015_32'
img_format = '*.JPEG'
data = glob(os.path.join(img_dir, img_format))
def deletegrayimg():
data_index = len(data)
for idx in range(0,len_data):
batch_file = data[idx]
img = scipy.misc.imread(batch_file)
img = img.astype(np.float)
img_shape = list(img.shape)
if len(img_shape) != 3:
print('img is not rgb:%d'%idx)
os.remove(batch_file)
else:
if img_shape[2] !=3:
print('shape[2] is not 3:%d'%idx)
os.remove(batch_file)
deletgrayimg()
以及图像缩放代码:
def changesize(img):
img_name = img
# 打开图片
oldimg = Image.open(path + img_name)
# 大小缩放为64*64
new_img = oldimg.resize((64,64))
# 以原名称存储图片
new_img.save(Newimg_Path + img_name)
for img in os.listdir(path):
# 不同格式
#print(img)
changesize(img)