TensorFlow 2.0 U-Net图像分割教程

什么是图像分割(image segmentatioin)?

想必你已经了解图像分类,神经网络所应用的任务之一就是对输入图像进行分类,指出其属于哪一类图像。然而,如果你需要从图像中识别出物体,指出图片中的像素点分别归属于什么物体,这种情况下你需要的是分割图像(segment the image),换句话说就是给图像的像素点打上标签。图像分割(image segmentation)的任务就是训练一个神经网络来,其输出为图片像素级别(pixel-wise)的mask。这可以帮助我们在像素层面上理解图片。图像分割技术有许多应用,如:医疗影像,自动驾驶,卫星图片处理。

本教程使用的数据集是Oxford-IIIT Pet Dataset,作者是Parkhi等。数据集包含了图片,其相关的标签,像素级的mask。mask基本上就是每一个像素点的标签。每个像素点都被分为3类:

  • Class 1 : 属于宠物的像素点
  • Class 2 : 宠物边界的像素点
  • Class 3 : 其它像素点,环境等
!pip install -q git+https://github.com/tensorflow/examples.git
try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass
import tensorflow as tf
from __future__ import absolute_import, division, print_function, unicode_literals

from tensorflow_examples.models.pix2pix import pix2pix

import tensorflow_datasets as tfds
tfds.disable_progress_bar()

from IPython.display import clear_output
import matplotlib.pyplot as plt

下载Oxford-IIIT Pets数据集

数据集已经集成在TensorFlow中,我们只需要下载即可。分割mask(segmentation masks)在3.0.0版本中才有提供,因此我们使用这一版本:

dataset, info = tfds.load('oxford_iiit_pet:3.0.0', with_info=True)

The following code performs a simple augmentation of flipping an image. In addition, image is normalized to [0,1]. Finally, as mentioned above the pixels in the segmentation mask are labeled either {1, 2, 3}. For the sake of convinience, let's subtract 1 from the segmentation mask, resulting in labels that are : {0, 1, 2}.

def normalize(input_image, input_mask):
  input_image = tf.cast(input_image, tf.float32)/128.0 - 1
  input_mask -= 1
  return input_image, input_mask
@tf.function
def load_image_train(datapoint):
  input_image = tf.image.resize(datapoint['image'], (128, 128))
  input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))

  if tf.random.uniform(()) > 0.5:
    input_image = tf.image.flip_left_right(input_image)
    input_mask = tf.image.flip_left_right(input_mask)

  input_image, input_mask = normalize(input_image, input_mask)

  return input_image, input_mask
def load_image_test(datapoint):
  input_image = tf.image.resize(datapoint['image'], (128, 128))
  input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))

  input_image, input_mask = normalize(input_image, input_mask)

  return input_image, input_mask

数据集本身需要分割训练和测试,以下我们对其进行分割:

TRAIN_LENGTH = info.splits['train'].num_examples
BATCH_SIZE = 64
BUFFER_SIZE = 1000
STEPS_PER_EPOCH = TRAIN_LENGTH // BATCH_SIZE
train = dataset['train'].map(load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE)
test = dataset['test'].map(load_image_test)
train_dataset = train.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()
train_dataset = train_dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
test_dataset = test.batch(BATCH_SIZE)

让我们以一个图片为例看一下,数据集里面的mask是什么效果:

def display(display_list):
  plt.figure(figsize=(15, 15))

  title = ['Input Image', 'True Mask', 'Predicted Mask']

  for i in range(len(display_list)):
    plt.subplot(1, len(display_list), i+1)
    plt.title(title[i])
    plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i]))
    plt.axis('off')
  plt.show()
for image, mask in train.take(1):
  sample_image, sample_mask = image, mask
display([sample_image, sample_mask])

定义模型

这里使用的是改进的U-Net。U-Net由一个下采样编码器 (downsampler)和上采样解码器 (upsampler)组成。为了能够学习到鲁棒的特征,并减少训练的参数,可以用一个预训练的模型充当编码器。本任务中编码器使用的是一个经过预训练的MobileNetV2模型,并应用其中间输出, 上采样解码器模块在Pix2pix tutorial的tensorflow例子实现。

有3个输出通道的原因是因为有像素点的分类有3种可能。

OUTPUT_CHANNELS = 3

如上,编码器是经过预训练的MobileNetV2,其已经在tf.keras.applications中集成。这个编码器包括了模型中介层(intermediate layer)的特别输出。请注意,编码器在训练过程(training process)中不会被训练。

base_model = tf.keras.applications.MobileNetV2(input_shape=[128, 128, 3], include_top=False)

# Use the activations of these layers
layer_names = [
    'block_1_expand_relu',   # 64x64
    'block_3_expand_relu',   # 32x32
    'block_6_expand_relu',   # 16x16
    'block_13_expand_relu',  # 8x8
    'block_16_project',      # 4x4
]
layers = [base_model.get_layer(name).output for name in layer_names]

# Create the feature extraction model
down_stack = tf.keras.Model(inputs=base_model.input, outputs=layers)

down_stack.trainable = False
Downloading data from https://github.com/JonathanCMitchell/mobilenet_v2_keras/releases/download/v1.1/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_128_no_top.h5
9412608/9406464 [==============================] - 2s 0us/step

解码器/上采样器是上采样模块的简单串联,以下是tensorflow的例子:

up_stack = [
    pix2pix.upsample(512, 3),  # 4x4 -> 8x8
    pix2pix.upsample(256, 3),  # 8x8 -> 16x16
    pix2pix.upsample(128, 3),  # 16x16 -> 32x32
    pix2pix.upsample(64, 3),   # 32x32 -> 64x64
]
def unet_model(output_channels):

  # This is the last layer of the model
  last = tf.keras.layers.Conv2DTranspose(
      output_channels, 3, strides=2,
      padding='same', activation='softmax')  #64x64 -> 128x128

  inputs = tf.keras.layers.Input(shape=[128, 128, 3])
  x = inputs

  # Downsampling through the model
  skips = down_stack(x)
  x = skips[-1]
  skips = reversed(skips[:-1])

  # Upsampling and establishing the skip connections
  for up, skip in zip(up_stack, skips):
    x = up(x)
    concat = tf.keras.layers.Concatenate()
    x = concat([x, skip])

  x = last(x)

  return tf.keras.Model(inputs=inputs, outputs=x)

训练模型

现在,让我们来编译和训练模型。这里的损失函数采用losses.sparse_categorical_crossentropy。选择这个损失函数的原因是任务的目标是对每个像素点进行分类,即是一个多分类预测问题。 在真正的segmentation mask中,每个像素点的标签是 {0,1,2}之一。网络的输出有3个通道。每个通道都要训练到,losses.sparse_categorical_crossentropy正适合这样的场景。网络的输出是像素点的标签,像素点的标签是得分最高的那个通道的代表值({0,1,2}之一)。 这是create_mask function所做的工作:

model = unet_model(OUTPUT_CHANNELS)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

我们先来看看,在训练前,预测结果是怎样的:

def create_mask(pred_mask):
  pred_mask = tf.argmax(pred_mask, axis=-1)
  pred_mask = pred_mask[..., tf.newaxis]
  return pred_mask[0]
def show_predictions(dataset=None, num=1):
  if dataset:
    for image, mask in dataset.take(num):
      pred_mask = model.predict(image)
      display([image[0], mask[0], create_mask(pred_mask)])
  else:
    display([sample_image, sample_mask,
             create_mask(model.predict(sample_image[tf.newaxis, ...]))])
show_predictions()

让我们观察一下训练带来的提升效果。为了完善这个工作,以下定义callback函数用来显示。

class DisplayCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs=None):
    clear_output(wait=True)
    show_predictions()
    print ('\nSample Prediction after epoch {}\n'.format(epoch+1))
EPOCHS = 20
VAL_SUBSPLITS = 5
VALIDATION_STEPS = info.splits['test'].num_examples//BATCH_SIZE//VAL_SUBSPLITS

model_history = model.fit(train_dataset, epochs=EPOCHS,
                          steps_per_epoch=STEPS_PER_EPOCH,
                          validation_steps=VALIDATION_STEPS,
                          validation_data=test_dataset,
                          callbacks=[DisplayCallback()])

Sample Prediction after epoch 20

57/57 [==============================] - 4s 73ms/step - loss: 0.1445 - accuracy: 0.9344 - val_loss: 0.3345 - val_accuracy: 0.8859
loss = model_history.history['loss']
val_loss = model_history.history['val_loss']

epochs = range(EPOCHS)

plt.figure()
plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'bo', label='Validation loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss Value')
plt.ylim([0, 1])
plt.legend()
plt.show()

预测

我们来进行预测,为了节省时间,epoch的数量不宜太大,但是要足够大以保证足够的准确度。

show_predictions(test_dataset, 3)

下一步

现在,你已经了解什么是图像分割以及如何进行图像分割,你可以尝试使用不同的intermediate layer作为输出,或者更进一步使用不同的预训练模型。你也可以尝试挑战自己,参加Kaggle上的Carvana image masking挑战赛。

你可以在Tensorflow Object Detection API 找到其他的模型用来进行训练。

原文链接:https://www.tensorflow.org/beta/tutorials/images/segmentation

  • 7
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值