数据扩充函数n

2024-09-24 22:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

只是有点头晕:我对这件事还不熟悉,所以请温柔一点

我正在尝试创建一个函数,它将移动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

我检查了输出的数据集,它似乎没有应用移位。有人能引导我过去吗


Tags: 数据函数代码图像警告原始数据shiftdef
1条回答
网友
1楼 · 发布于 2024-09-24 22:30:23

与其编写自己的函数来实现这一点,不如依赖高级机器学习/深度学习模块提供的内置函数

与Keras模块一样,有一个名为ImageDataGenerator()的内置函数

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

width_shift_range,
height_shift_range

这些参数中的每一个都采用:一个Float、一个类似于1-D的数组或一个int

(1)。浮动:总高度的分数,如果<;1或像素,如果>;=1

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

(3)。int:间隔中的整数像素数(-height\u shift\u range,+height\u shift\u 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(),您还可以提供其他参数,如亮度、缩放、垂直翻转、水平翻转等。有关更多此类参数,请查看documentation

相关问题 更多 >