最近做深度学习有遇到图像通道数不同而产生输入与预期不符:
expected input(*,*,3)but (*,*,3)
这是因为rgb图像中混杂着灰度图像导致通道数不唯一
本来想着就写个代码把灰度图删掉
import os
from PIL import Image
import numpy as np
contents = ['Abyssinian', 'Bengal', 'Calico', 'Domestic Long Hair', 'Egyptian Mau', 'Havana', 'Himalayan', 'Tabby',
'Tiger', 'Turkish Van']
def is_gray(img, threshold=10):
if len(img.getbands()) == 1:
return True
img1 = np.asarray(img.getchannel(channel=0), dtype=np.int16)
img2 = np.asarray(img.getchannel(channel=1), dtype=np.int16)
img3 = np.asarray(img.getchannel(channel=2), dtype=np.int16)
diff1 = (img1 - img2).var()
diff2 = (img2 - img3).var()
diff3 = (img3 - img1).var()
diff_sum = (diff1 + diff2 + diff3) / 3.0
if diff_sum <= threshold:
return True
else:
return False
for content in contents:
for img_path in os.listdir('./images/' + content):
#img = open('./images/' + content + '/' + img_path,'rb')
img = Image.open('./images/' + content + '/' + img_path)
if is_gray(img):
os.remove('./images/' + content + '/' + img_path)
却又出现新的报错:程序已被占用,最后发现只是打开了图片没有及时关掉而已
更新代码如下:
至此问题解决
import os
from PIL import Image
import numpy as np
contents = ['Abyssinian', 'Bengal', 'Calico', 'Domestic Long Hair', 'Egyptian Mau', 'Havana', 'Himalayan', 'Tabby',
'Tiger', 'Turkish Van']
def is_gray(img, threshold=10):
if len(img.getbands()) == 1:
return True
img1 = np.asarray(img.getchannel(channel=0), dtype=np.int16)
img2 = np.asarray(img.getchannel(channel=1), dtype=np.int16)
img3 = np.asarray(img.getchannel(channel=2), dtype=np.int16)
diff1 = (img1 - img2).var()
diff2 = (img2 - img3).var()
diff3 = (img3 - img1).var()
diff_sum = (diff1 + diff2 + diff3) / 3.0
if diff_sum <= threshold:
return True
else:
return False
for content in contents:
for img_path in os.listdir('./images/' + content):
#img = open('./images/' + content + '/' + img_path,'rb')
img = Image.open('./images/' + content + '/' + img_path)
if is_gray(img):
img.close()
os.remove('./images/' + content + '/' + img_path)