[关闭]
@BruceWang 2018-01-21T07:44:13.000000Z 字数 11830 阅读 2363

用Keras和直方图均衡化进行深度学习的图像增强

数据增强


一、我遇到了啥子问题撒~?


我现在写的文章都是因为遇到问题了,然后把解决过程给大家呈现出来

那么,现在我遇到了一个医学图像处理问题。

最近在处理医学图像的问题,发现DataSet一共只有400张图像,还是分为四类。

cancer

那怎么办呢?
可能你会说:这还不简单,迁移学习啊
soga,小伙子可以啊,不过今天我们不讲它(因为我还没实践过)

在这篇文章中,我们将讨论并解决此问题:

二、我怎么解决的嘞?

  • 图像增强:它是什么?它为什么如此重要?
  • Keras:如何将它用于基本的图像增强。
  • 直方图均衡化:这是什么?它有什么用处?
  • 实现直方图均衡技术:修改keras.preprocessing image.py文件的一种方法。

三、我怎么做的嘞?

接下来我会从这四方面来讨论解决数据不足的问题

1.图像增强:它是什么?它为什么如此重要?

深度神经网络,尤其是卷积神经网络(CNN),尤其擅长图像分类任务。最先进的CNN甚至已经被证明超过了人类在图像识别方面的表现。

matric

image source:https://www.eff.org/ai/metrics

如果想克服收集数以千计的训练图像的高昂费用,图像增强则就是从现有数据集生成训练数据。
图像增强是将已经存在于训练数据集中的图像进行处理,并对其进行处理以创建相同图像的许多改变的版本。

这既提供了更多的图像来训练,也可以帮助我们的分类器暴露在更广泛的俩个都和色彩情况下,从而使我们的分类器更具有鲁棒性,以下是imgaug库中不同增强的一些示例

cats

source image:https://github.com/aleju/imgaug

2.使用Keras进行基本图像增强

有很多方法来预处理图像,在这篇文章中,我借鉴使用keras深度学习库为增强图像提供的一些最常用的开箱即用方法,然后演示如何修改keras.preprocessing image.py文件以启用直方图均衡化方法。

我们将使用keras自带的cifar10数据集。但是,我们只会使用数据集中的猫和狗的图像,以便保持足够小的任务在CPU上执行。

我们要做的第一件事就是加载cifar10数据集并格式化图像,为CNN做准备。
我们还会仔细查看一些图像,以确保数据已正确加载

先偷看一下长什么样?

  1. 16]:
  2. from __future__ import print_function
  3. import keras
  4. from keras.datasets import cifar10
  5. from keras import backend as K
  6. import matplotlib
  7. from matplotlib import pyplot as plt
  8. import numpy as np
  9. # input image dimensions
  10. img_rows, img_cols = 32, 32
  11. # the data, shuffled and split between train and test sets
  12. (x_train, y_train), (x_test, y_test) = cifar10.load_data()
  13. # Only look at cats [=3] and dogs [=5]
  14. train_picks = np.ravel(np.logical_or(y_train==3,y_train==5))
  15. test_picks = np.ravel(np.logical_or(y_test==3,y_test==5))
  16. y_train = np.array(y_train[train_picks]==5,dtype=int)
  17. y_test = np.array(y_test[test_picks]==5,dtype=int)
  18. x_train = x_train[train_picks]
  19. x_test = x_test[test_picks]
  20. ...
  21. ...
  22. ...
  23. images = range(0,9)
  24. for i in images:
  25. plt.subplot(330 + 1 + i)
  26. plt.imshow(x_train[i], cmap=pyplot.get_cmap('gray'))
  27. # show the plot
  28. plt.show()
  1. 此处代码参考链接地址:https://github.com/ryanleeallred/Image_Augmentation/blob/master/Histogram_Modification.ipynb

load_and_show

cifar10图像只有32 x 32像素,所以在这里放大时看起来有颗粒感,但是CNN并不知道它有颗粒感,只能看到数据, 嗯,还是人类牛逼。

用keras增强 图像数据 非常简单。 Jason Brownlee 对此提供了一个很好的教程

首先,我们需要通过调用ImageDataGenerator()函数来创建一个图像生成器,并将它传递给我们想要在图像上执行的变化的参数列表。

然后,我们将调用fit()我们的图像生成器的功能,这将逐批地应用到图像的变化。默认情况下,这些修改将被随机应用,所以并不是每一个图像都会被改变。大家也可以使用keras.preprocessing导出增强的图像文件到一个文件夹,以便建立一个巨大的数据集的改变图像,如果你想这样做,可以参考keras文档

  1. # Rotate images by 90 degrees
  2. datagen = ImageDataGenerator(rotation_range=90)
  3. # fit parameters from data
  4. datagen.fit(x_train)
  5. # Configure batch size and retrieve one batch of images
  6. for X_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9):
  7. # Show 9 images
  8. for i in range(0, 9):
  9. pyplot.subplot(330 + 1 + i)
  10. pyplot.imshow(X_batch[i].reshape(img_rows, img_cols, 3))
  11. # show the plot
  12. pyplot.show()
  13. break

rotate

  1. # Flip images vertically
  2. datagen = ImageDataGenerator(vertical_flip=True)
  3. # fit parameters from data
  4. datagen.fit(x_train)
  5. # Configure batch size and retrieve one batch of images
  6. for X_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9):
  7. # Show 9 images
  8. for i in range(0, 9):
  9. pyplot.subplot(330 + 1 + i)
  10. pyplot.imshow(X_batch[i].reshape(img_rows, img_cols, 3))
  11. # show the plot
  12. pyplot.show()
  13. break

flip

备注:我感觉这里需要针对数据集,因为很少有人把狗翻过来看,或者拍照(hahhhh)

  1. # Shift images vertically or horizontally
  2. # Fill missing pixels with the color of the nearest pixel
  3. datagen = ImageDataGenerator(width_shift_range=.2,
  4. height_shift_range=.2,
  5. fill_mode='nearest'
  6. )
  7. # fit parameters from data
  8. datagen.fit(x_train)
  9. # Configure batch size and retrieve one batch of images
  10. for X_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9):
  11. # Show 9 images
  12. for i in range(0, 9):
  13. pyplot.subplot(330 + 1 + i)
  14. pyplot.imshow(X_batch[i].reshape(img_rows, img_cols, 3))
  15. # show the plot
  16. pyplot.show()
  17. break

shift

3.直方图均衡技术

直方图均衡化是指对比度较低的图像,并增加图像相对高低的对比度,以便在阴影中产生细微的差异,并创建较高的对比度图像。结果可能是惊人的,特别是对于灰度图像,如图

person

使用图像增强技术来提高图像的对比度,此方法有时也被称为“ 直方图拉伸
”,因为它们采用像素强度的分布和拉伸分布来适应更宽范围的值,从而增加图像的最亮部分和最暗部分之间的对比度水平。

eyes

直方图均衡
直方图均衡通过检测图像中像素密度的分布并将这些像素密度绘制在直方图上来增加图像的对比度。然后分析该直方图的分布,并且如果存在当前未被使用的像素亮度范围,则直方图被“拉伸”以覆盖这些范围,然后被“
反投影 ”到图像上以增加总体形象的对比

histogram

自适应均衡
自适应均衡与常规直方图均衡的不同之处在于计算几个不同的直方图,每个直方图对应于图像的不同部分;
然而,在其他无趣的部分有过度放大噪声的倾向。

下面的代码来自于sci-kit图像库的文档,并且已经被修改为在我们的cifar10数据集的第一个图像上执行上述三个增强。

首先,我们将从sci-kit图像(skimage)库中导入必要的模块,然后修改sci-kit图像文档中的代码以查看数据集第一幅图像上的增强

  1. # Import skimage modules
  2. from skimage import data, img_as_float
  3. from skimage import exposure
  4. # Lets try augmenting a cifar10 image using these techniques
  5. from skimage import data, img_as_float
  6. from skimage import exposure
  7. # Load an example image from cifar10 dataset
  8. img = images[0]
  9. # Set font size for images
  10. matplotlib.rcParams['font.size'] = 8
  11. # Contrast stretching
  12. p2, p98 = np.percentile(img, (2, 98))
  13. img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
  14. # Histogram Equalization
  15. img_eq = exposure.equalize_hist(img)
  16. # Adaptive Equalization
  17. img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03)
  18. #### Everything below here is just to create the plot/graphs ####
  19. # Display results
  20. fig = plt.figure(figsize=(8, 5))
  21. axes = np.zeros((2, 4), dtype=np.object)
  22. axes[0, 0] = fig.add_subplot(2, 4, 1)
  23. for i in range(1, 4):
  24. axes[0, i] = fig.add_subplot(2, 4, 1+i, sharex=axes[0,0], sharey=axes[0,0])
  25. for i in range(0, 4):
  26. axes[1, i] = fig.add_subplot(2, 4, 5+i)
  27. ax_img, ax_hist, ax_cdf = plot_img_and_hist(img, axes[:, 0])
  28. ax_img.set_title('Low contrast image')
  29. y_min, y_max = ax_hist.get_ylim()
  30. ax_hist.set_ylabel('Number of pixels')
  31. ax_hist.set_yticks(np.linspace(0, y_max, 5))
  32. ax_img, ax_hist, ax_cdf = plot_img_and_hist(img_rescale, axes[:, 1])
  33. ax_img.set_title('Contrast stretching')
  34. ax_img, ax_hist, ax_cdf = plot_img_and_hist(img_eq, axes[:, 2])
  35. ax_img.set_title('Histogram equalization')
  36. ax_img, ax_hist, ax_cdf = plot_img_and_hist(img_adapteq, axes[:, 3])
  37. ax_img.set_title('Adaptive equalization')
  38. ax_cdf.set_ylabel('Fraction of total intensity')
  39. ax_cdf.set_yticks(np.linspace(0, 1, 5))
  40. # prevent overlap of y-axis labels
  41. fig.tight_layout()
  42. plt.show()

hist_result

4.修改keras.preprocessing以启用直方图均衡技术。

现在我们已经成功地从cifar10数据集中修改了一个图像,我们将演示如何修改keras.preprocessing
image.py文件,以执行这些不同的直方图修改技术,就像我们开箱即可使用的keras增强使用ImageDataGenerator()。

以下是我们将要执行此功能的一般步骤:

  • 在你自己的机器上找到keras.preprocessing image.py文件。
  • 将image.py文件复制到您的文件或笔记本中。
  • 为每个均衡技术添加一个属性到DataImageGenerator()init函数。
  • 将IF语句子句添加到random_transform方法,以便在我们调用时实现增强datagen.fit()。

对keras.preprocessing

image.py文件进行修改的最简单方法之一就是将其内容复制并粘贴到我们的代码中。这将删除需要导入它。为了确保您抓取的是之前导入的文件的相同版本,最好抓取image.py您计算机上已有的文件。
运行print(keras.__file__)将打印出机器上keras库的路径。路径(对于mac用户)可能如下所示:

/usr/local/lib/python3.5/dist-packages/keras/__init__.pyc

这给了我们在本地机器上keras的路径。

继续前进,在那里导航,然后进入preprocessing文件夹在里面preprocessing你会看到image.py文件。然后您可以将其内容复制到您的代码中。该文件很长,但对于初学者来说,这可能是最简单的方法之一。

编辑 image.py

在image.py的顶部,你可以注释掉这行:from ..import backend as K如果你已经包含在上面。

此时,请仔细检查以确保您正在导入必要的scikit-image模块,以便复制的模块image.py可以看到它们。

from skimage import data, img_as_float
from skimage import exposure

我们现在需要在ImageDataGenerator类的 __ init __
方法中添加六行代码,以便它具有三个代表我们要添加的增强类型的属性。下面的代码是从我目前的image.py中复制的。与#####侧面的线是我已经添加的线

  1. def __init__(self,
  2. contrast_stretching=False, #####
  3. histogram_equalization=False,#####
  4. adaptive_equalization=False, #####
  5. featurewise_center=False,
  6. samplewise_center=False,
  7. featurewise_std_normalization=False,
  8. samplewise_std_normalization=False,
  9. zca_whitening=False,
  10. rotation_range=0.,
  11. width_shift_range=0.,
  12. height_shift_range=0.,
  13. shear_range=0.,
  14. zoom_range=0.,
  15. channel_shift_range=0.,
  16. fill_mode=’nearest’,
  17. cval=0.,
  18. horizontal_flip=False,
  19. vertical_flip=False,
  20. rescale=None,
  21. preprocessing_function=None,
  22. data_format=None):
  23. if data_format is None:
  24. data_format = K.image_data_format()
  25. self.counter = 0
  26. self.contrast_stretching = contrast_stretching, #####
  27. self.adaptive_equalization = adaptive_equalization #####
  28. self.histogram_equalization = histogram_equalization #####
  29. self.featurewise_center = featurewise_center
  30. self.samplewise_center = samplewise_center
  31. self.featurewise_std_normalization = featurewise_std_normalization
  32. self.samplewise_std_normalization = samplewise_std_normalization
  33. self.zca_whitening = zca_whitening
  34. self.rotation_range = rotation_range
  35. self.width_shift_range = width_shift_range
  36. self.height_shift_range = height_shift_range
  37. self.shear_range = shear_range
  38. self.zoom_range = zoom_range
  39. self.channel_shift_range = channel_shift_range
  40. self.fill_mode = fill_mode
  41. self.cval = cval
  42. self.horizontal_flip = horizontal_flip
  43. self.vertical_flip = vertical_flip
  44. self.rescale = rescale
  45. self.preprocessing_function = preprocessing_function

该random_transform()(下)函数来响应我们一直传递到的参数ImageDataGenerator()功能。

如果我们已经设置了contrast_stretching,adaptive_equalization或者histogram_equalization参数True,当我们调用ImageDataGenerator()时(就像我们对其他图像增强一样)random_transform()将会应用所需的图像增强。

  1. def random_transform(self, x):
  2. img_row_axis = self.row_axis - 1
  3. img_col_axis = self.col_axis - 1
  4. img_channel_axis = self.channel_axis - 1
  5. # use composition of homographies
  6. # to generate final transform that needs to be applied
  7. if self.rotation_range:
  8. theta = np.pi / 180 * np.random.uniform(-self.rotation_range, self.rotation_range)
  9. else:
  10. theta = 0
  11. if self.height_shift_range:
  12. tx = np.random.uniform(-self.height_shift_range, self.height_shift_range) * x.shape[img_row_axis]
  13. else:
  14. tx = 0
  15. if self.width_shift_range:
  16. ty = np.random.uniform(-self.width_shift_range, self.width_shift_range) * x.shape[img_col_axis]
  17. else:
  18. ty = 0
  19. if self.shear_range:
  20. shear = np.random.uniform(-self.shear_range, self.shear_range)
  21. else:
  22. shear = 0
  23. if self.zoom_range[0] == 1 and self.zoom_range[1] == 1:
  24. zx, zy = 1, 1
  25. else:
  26. zx, zy = np.random.uniform(self.zoom_range[0], self.zoom_range[1], 2)
  27. transform_matrix = None
  28. if theta != 0:
  29. rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
  30. [np.sin(theta), np.cos(theta), 0],
  31. [0, 0, 1]])
  32. transform_matrix = rotation_matrix
  33. if tx != 0 or ty != 0:
  34. shift_matrix = np.array([[1, 0, tx],
  35. [0, 1, ty],
  36. [0, 0, 1]])
  37. transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)
  38. if shear != 0:
  39. shear_matrix = np.array([[1, -np.sin(shear), 0],
  40. [0, np.cos(shear), 0],
  41. [0, 0, 1]])
  42. transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)
  43. if zx != 1 or zy != 1:
  44. zoom_matrix = np.array([[zx, 0, 0],
  45. [0, zy, 0],
  46. [0, 0, 1]])
  47. transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix)
  48. if transform_matrix is not None:
  49. h, w = x.shape[img_row_axis], x.shape[img_col_axis]
  50. transform_matrix = transform_matrix_offset_center(transform_matrix, h, w)
  51. x = apply_transform(x, transform_matrix, img_channel_axis,
  52. fill_mode=self.fill_mode, cval=self.cval)
  53. if self.channel_shift_range != 0:
  54. x = random_channel_shift(x, self.channel_shift_range, img_channel_axis)
  55. if self.horizontal_flip:
  56. if np.random.random() < 0.5:
  57. x = flip_axis(x, img_col_axis)
  58. if self.vertical_flip:
  59. if np.random.random() < 0.5:
  60. x = flip_axis(x, img_row_axis)
  61. if self.contrast_stretching: #####
  62. if np.random.random() < 0.5: #####
  63. p2, p98 = np.percentile(x, (2, 98)) #####
  64. x = exposure.rescale_intensity(x, in_range=(p2, p98)) #####
  65. if self.adaptive_equalization: #####
  66. if np.random.random() < 0.5: #####
  67. x = exposure.equalize_adapthist(x, clip_limit=0.03) #####
  68. if self.histogram_equalization: #####
  69. if np.random.random() < 0.5: #####
  70. x = exposure.equalize_hist(x) #####
  71. return x

现在我们拥有所有必要的代码,并且可以调用ImageDataGenerator()来执行我们的直方图修改技术。如果我们将所有三个值都设置为,则这是几张图片的样子True

  1. # Initialize Generator
  2. datagen = ImageDataGenerator(contrast_stretching=True, adaptive_equalization=True, histogram_equalization=True)
  3. # fit parameters from data
  4. datagen.fit(x_train)
  5. # Configure batch size and retrieve one batch of images
  6. for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9):
  7. # Show the first 9 images
  8. for i in range(0, 9):
  9. pyplot.subplot(330 + 1 + i)
  10. pyplot.imshow(x_batch[i].reshape(img_rows, img_cols, 3))
  11. # show the plot
  12. pyplot.show()
  13. break

result

最后一步是训练CNN并验证模型model.fit_generator(),以便在增强图像上训练和验证我们的神经网络.

  1. from keras.models import Sequential
  2. from keras.layers import Dense, Dropout, Flatten
  3. from keras.layers import Conv2D, MaxPooling2D
  4. batch_size = 64
  5. num_classes = 2
  6. epochs = 10
  7. model = Sequential()
  8. model.add(Conv2D(4, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
  9. model.add(Conv2D(8, (3, 3), activation='relu'))
  10. model.add(MaxPooling2D(pool_size=(2, 2)))
  11. model.add(Dropout(0.25))
  12. model.add(Flatten())
  13. model.add(Dense(16, activation='relu'))
  14. model.add(Dropout(0.5))
  15. model.add(Dense(2, activation='softmax'))
  16. model.compile(loss=keras.losses.categorical_crossentropy,
  17. optimizer=keras.optimizers.Adadelta(),
  18. metrics=['accuracy'])
  19. datagen.fit(x_train)
  20. history = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),
  21. steps_per_epoch=x_train.shape[0] // batch_size,
  22. epochs=20,
  23. validation_data=(x_test, y_test))

train_result

End 总结

这是我最后的测试结果

my_augmentation

左上、增强测试图片 右上、增强结果

左下、原始数据标签 右下、原始数据

大家自己尝试一下哈,加油!

如果你有什么疑问,欢迎联系我哈,我会给大家慢慢解答啦~~~怎么联系我? 笨啊~ ~~ 你留言也行
你关注微信公众号1.听朕给你说:2.tzgns666,3.或者扫那个二维码,后台联系我也行啦!
tzgns666

终于写完了,赞赏一下下嘛!

(爱心.gif) 么么哒~么么哒~么么哒
爱心从我做起,贫困山区捐衣服,为开源社区做贡献!

码字不易啊,如果你觉得本文有帮助,三毛也是爱!真的就三毛,呜呜。。。我祝各位帅哥,和美女,你们永远十八岁,嗨嘿嘿~~~

weiChat
Alibaba

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注