好的,感谢this article,我终于找到了解决这些问题的方法。我的错误是我一直使用ImageDataGenerator,尽管它缺乏灵活性,但解决方案很简单:使用另一个数据增强工具。
我们可以恢复作者的方法如下:
- 首先,创建一个个性化批处理生成器作为 Keras
Sequence 类的子类(这意味着要实现一个 __getitem__ 函数,根据图像各自的路径加载图像)。
-
使用数据增强 albumentations 库。它的优点是提供更多的转换功能,如
Imgaug或ImageDataGenerator,同时速度更快。此外,this website 允许您测试它的一些增强方法,甚至使用您自己的图像!有关详细列表,请参阅 this one。
这个库的缺点是,由于它相对较新,所以在网上可以找到很少的文档,我花了几个小时试图解决我遇到的问题。
确实,当我试图可视化一些增强函数时,结果是完全黑色的图像(奇怪的事实:只有当我使用 RandomGamma 或 RandomBrightnessContrast 等方法修改像素的强度时才会发生这种情况。 HorizontalFlip或ShiftScaleRotate等转换函数,可以正常工作)。
经过整整半天的尝试找出问题所在,我最终想出了这个解决方案,如果你想尝试这个库,这可能会对你有所帮助:必须完成图像的加载使用 OpenCV(我使用来自 tf.keras.preprocessing.image 的 load_img 和 img_to_array 函数进行加载和处理)。如果有人解释为什么这不起作用,我会很高兴听到它。
无论如何,这是我显示增强图像的最终代码:
!pip install -U git+https://github.com/albu/albumentations > /dev/null && echo "All libraries are successfully installed!"
from albumentations import Compose, HorizontalFlip, RandomBrightnessContrast, ToFloat, RGBShift
import cv2
import matplotlib.pyplot as plt
import numpy as np
from google.colab.patches import cv2_imshow # I work on a Google Colab, thus I cannot use cv2.imshow()
augmentation = Compose([HorizontalFlip(p = 0.5),
RandomBrightnessContrast(p = 1),
ToFloat(max_value = 255) # Normalize the pixels values into the [0,1] interval
# Feel free to add more !
])
img = cv2.imread('Your_path_here.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # cv2.imread() loads the images in BGR format, thus you have to convert it to RGB before applying any transformation function.
img = augmentation(image = img)['image'] # Apply the augmentation functions to the image.
plt.figure(figsize=(7, 7))
plt.imshow((img*255).astype(np.uint8)) # Put the pixels values back to [0,255]. Replace by plt.imshow(img) if the ToFloat function is not used.
plt.show()
'''
If you want to display using cv2_imshow(), simply replace the last three lines by :
img = cv2.normalize(img, None, 255,0, cv2.NORM_MINMAX, cv2.CV_8UC1) # if the ToFloat argument is set up inside Compose(), you have to put the pixels values back to [0,255] before plotting them with cv2_imshow(). I couldn't try with cv2.imshow(), but according to the documentation it seems this line would be useless with this displaying function.
cv2_imshow(img)
I don't recommend it though, because cv2_imshow() plot the images in BGR format, thus some augmentation methods such as RGBShift will not work properly.
'''
编辑:
我在 albumentations 库中遇到了几个问题(我在 Github 上的 this question 中进行了描述,但目前我仍然没有答案)因此 我最好推荐使用 Imgaug你的数据增强:它工作得很好,几乎和albumentations 一样容易使用,尽管可用的转换函数有点少。