最近申请基金,想到一个idea,将常见的三维图片训练集处理为四维模糊图片,用四维图片训练集训练模型,比较新模型和旧模型的准确率。
网上找了一大堆,有两个博客提出这个问题,下面的回复都没什么卵用。
这里实现一个简单的四维矩阵存储多张一维图片例子,供大家参考。
对于通道的定义,比如原图是RGB3通道,一千张图片放到四维矩阵,通道数还是3。
之前给的代码太繁琐,这里重新修改简化了,方便读者理解和实现。
read_file函数的作用就是读取文件夹下所有的猫狗图片,每读取一张,进行三种不同程度的高斯模糊之后,定义一个四维矩阵,将包括原图在内的四张图片添加到四维矩阵中,生成一张新的图片
def endwith(s,*endstring):
resultArray = map(s.endswith,endstring)
if True in resultArray:
return True
else:
return False
#猫狗数据集
def read_file(path):
img_list = []
label_list = []
dir_counter = 0
# 对路径下的所有子文件夹中的所有jpg文件进行读取并存入到一个list中
for child_dir in os.listdir(path):
child_path = os.path.join(path, child_dir)
for dir_image in os.listdir(child_path):
if endwith(dir_image, 'jpg'):
img = Image.open(os.path.join(child_path, dir_image))
#图片归一化处理
img=img.resize((255,255))
arr = np.asarray(img, dtype="float32")
#高斯模糊处理
image1 = img.filter(GaussianBlur(radius=1))
arr1 = np.asarray(image1, dtype="float32")
image2 = img.filter(GaussianBlur(radius=3))
arr2 = np.asarray(image2, dtype="float32")
image3 = img.filter(GaussianBlur(radius=5))
arr3 = np.asarray(image3, dtype="float32")
#合成四维矩阵,将图片逐个放到矩阵中
new = np.empty((255, 255, 3, 4), dtype="float32")#最后一维是图片index
new[:, :, :, 0] = arr
new[:, :, :, 1] = arr1
new[:, :, :, 2] = arr2
new[:, :, :, 3] = arr3
img_list.append(new)
label_list.append(dir_counter)
dir_counter += 1
# 返回的img_list转成了 np.array的格式
img_list = np.array(img_list)
return img_list, label_list