我需要进行数据增强,但不需要任何填充模式,constant
、reflect
、nearest
、wrap
。相反,每次旋转或平移图像时,我都希望对其进行中心裁剪(如下所示),以便没有任何黑色、白色、反射或恒定的边缘/边框,如所述 here .
如何在考虑到这些点的情况下扩展 ImageDataGenerator
类(如果这是唯一的方法,并且没有开箱即用的中心裁剪)?
保留 ImageDataGenerator 的现有部分除了增强部分之外,编写自定义增强函数
在增强发生之前保留原始尺寸的图像而不调整大小会是有效的,因为调整大小后中心裁剪会导致大量数据丢失。 平移/旋转 -> 居中裁剪 -> 调整大小
应该比 调整大小 -> 平移/旋转 -> 居中裁剪
更高效
如果有人正在寻找解决方案,以下是我解决问题的方法。主要思想是将 ImageDataGenerator 包装在自定义生成器中,如下所示:
def crop_generator(batches, new_size):
while True:
batch_x, batch_y = next(batches)
x= batch_x.shape[1] // 2
y= batch_x.shape[2] // 2
size = new_size // 2
yield (batch_x[:, x-size:x+size, y-size:y+size], batch_y)
x_train = HDF5Matrix(...)
y_train = HDF5Matrix(...)
datagen = ImageDataGenerator(rotation_range=180, ...)
model = create_model()
training_gen = crop_generator(datagen.flow(x_train, y_train, batch_size=128), new_size=64)
model.fit_generator(training_gen, ...)
使用numpy索引batch_x[:, x-size:x+size, y-size:y+size, :]
我们只改变x
和图像的 y
尺寸,保持批量大小和 channel 尺寸相同。这使我们能够避免 for 循环。
我是一名优秀的程序员,十分优秀!