数据增强功能不正确



抬起头来:我是新手,所以请温柔一点。

我正在尝试创建一个函数,该函数将移动 MNIST 数据集中的每个图像并将移位的图像添加到原始数据集中,从而有效地将数据集大小加倍。

我的代码(警告,它可能是一个热混乱,我最终必须学习如何编写更优雅的函数(:

def four_point(i_set):
o_set = i_set
for i in i_set:
copy1 = np.ndarray(shape=(28,28))
shift(i, shift=(1,0), output=copy1)
copy1 = copy1.reshape(1,28,28)
o_set = np.concatenate((o_set, copy1))
return o_set

我已经检查了输出的数据集,它似乎没有应用移位。谁能引导我过去这个?

与其编写自己的函数来执行此操作,不如依靠更高级别的机器学习/深度学习模块提供的内置函数。

就像在 Keras 模块中一样,有一个名为 ImageDataGenerator(( 的内置函数。

此函数有两个参数用于在图像中生成偏移。一个用于水平移位,另一个用于垂直移位。这两个参数是:

width_shift_range,
height_shift_range

这些参数中的每一个都采用:浮点型、类似一维数组或整数。

1(. 浮点数:如果<1,则占总高度的分数,如果>= 1,则像素。

2(. 一维数组样:数组中的随机元素。

3(. int:来自间隔(-height_shift_range、+height_shift_range(的整数像素数

现在,考虑到您想要增强这些图像并将它们全部保存在同一个文件夹中的事实,请使用这段代码:

aug = ImageDataGenerator(width_shift_range=0.2,height_shift_range=0.2)
### Make sure to have "/" at the end of the path
list_of_images=os.listdir("/path/to/the/folder/of/images/")
total = 0
#Change the value of "const" to the number of new augmented images to be created
const= 300
for i in range(const):
curr_image = random.choice(list_of_images)
image = load_img("/path/to/the/folder/of/images/"+curr_image)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
imageGen = aug.flow(image, batch_size=1, save_to_dir='/path/to/folder/to/save/images/',save_prefix="augment_image",save_format="jpg")
for image in imageGen:
total += 1
if total == const:
break
break

上面的代码片段将在名为"/path/to/folder/to/save/images/"的文件夹中创建 300 个新图像。然后,您所要做的就是将原始图像粘贴到此文件夹中。

您还可以为 ImageDataGenerator(( 提供其他参数,如亮度、缩放、垂直翻转、水平翻转等。请查看文档以获取更多此类参数。

最新更新