ถ่ายทอดสไตล์ศิลปะด้วย TensorFlow Lite

ดูบน TensorFlow.org ทำงานใน Google Colab ดูแหล่งที่มาบน GitHub ดาวน์โหลดโน๊ตบุ๊ค ดูรุ่น TF Hub

หนึ่งของการพัฒนาที่น่าตื่นเต้นที่สุดในการเรียนรู้ลึกที่จะออกมาเมื่อเร็ว ๆ นี้คือ การถ่ายโอนรูปแบบศิลปะ หรือความสามารถในการสร้างภาพใหม่ที่เรียกว่า pastiche อยู่บนพื้นฐานของการป้อนข้อมูลสองภาพหนึ่งที่เป็นตัวแทนของรูปแบบศิลปะและเป็นหนึ่งในตัวแทนของเนื้อหา

ตัวอย่างการถ่ายโอนสไตล์

เมื่อใช้เทคนิคนี้ เราสามารถสร้างงานศิลปะใหม่ๆ ที่สวยงามได้ในหลากหลายสไตล์

ตัวอย่างการถ่ายโอนสไตล์

หากคุณเพิ่งเริ่มใช้ TensorFlow Lite และกำลังใช้งาน Android เราขอแนะนำให้คุณสำรวจแอปพลิเคชันตัวอย่างต่อไปนี้ซึ่งจะช่วยให้คุณเริ่มต้นได้

Android เช่น iOS ของคุณตัวอย่างเช่น

หากคุณกำลังใช้แพลตฟอร์มอื่น ๆ นอกเหนือจาก Android หรือ iOS หรือคุณคุ้นเคยกับ TensorFlow Lite API ที่ คุณสามารถทำตามการกวดวิชานี้จะเรียนรู้วิธีการใช้การถ่ายโอนสไตล์คู่ใด ๆ ของเนื้อหาและภาพรูปแบบที่มีก่อนการฝึกอบรม TensorFlow Lite แบบอย่าง. คุณสามารถใช้โมเดลเพื่อเพิ่มการถ่ายโอนสไตล์ไปยังแอปพลิเคชันมือถือของคุณเอง

รุ่นที่เปิดมาบน GitHub คุณสามารถฝึกโมเดลใหม่ด้วยพารามิเตอร์ต่างๆ (เช่น เพิ่มน้ำหนักของเลเยอร์เนื้อหาเพื่อให้ภาพที่ส่งออกดูเหมือนรูปภาพเนื้อหามากขึ้น)

ทำความเข้าใจสถาปัตยกรรมแบบจำลอง

สถาปัตยกรรมจำลอง

โมเดล Artistic Style Transfer นี้ประกอบด้วยโมเดลย่อยสองแบบ:

  1. สไตล์ Prediciton Model: A MobilenetV2 ตามเครือข่ายประสาทที่ใช้ภาพรูปแบบการป้อนไปยัง 100 มิติรูปแบบเวกเตอร์คอขวด
  2. รูปแบบการแปลง Model: A เครือข่ายประสาทที่จะใช้เวกเตอร์รูปแบบคอขวดกับภาพเนื้อหาและการสร้างภาพสวยเก๋

หากแอปของคุณต้องการสนับสนุนเฉพาะชุดรูปภาพสไตล์คงที่ คุณสามารถคำนวณเวกเตอร์คอขวดของสไตล์ได้ล่วงหน้า และยกเว้นรูปแบบการทำนายลักษณะจากไบนารีของแอป

ติดตั้ง

นำเข้าการอ้างอิง

import tensorflow as tf
print(tf.__version__)
2.6.0
import IPython.display as display

import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (12,12)
mpl.rcParams['axes.grid'] = False

import numpy as np
import time
import functools

ดาวน์โหลดเนื้อหาและรูปภาพสไตล์ และรุ่น TensorFlow Lite ที่ผ่านการฝึกอบรมล่วงหน้า

content_path = tf.keras.utils.get_file('belfry.jpg','https://storage.googleapis.com/khanhlvg-public.appspot.com/arbitrary-style-transfer/belfry-2611573_1280.jpg')
style_path = tf.keras.utils.get_file('style23.jpg','https://storage.googleapis.com/khanhlvg-public.appspot.com/arbitrary-style-transfer/style23.jpg')

style_predict_path = tf.keras.utils.get_file('style_predict.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite')
style_transform_path = tf.keras.utils.get_file('style_transform.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite')
Downloading data from https://storage.googleapis.com/khanhlvg-public.appspot.com/arbitrary-style-transfer/belfry-2611573_1280.jpg
458752/458481 [==============================] - 0s 0us/step
466944/458481 [==============================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/khanhlvg-public.appspot.com/arbitrary-style-transfer/style23.jpg
114688/108525 [===============================] - 0s 0us/step
122880/108525 [=================================] - 0s 0us/step
Downloading data from https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite
2834432/2828838 [==============================] - 0s 0us/step
2842624/2828838 [==============================] - 0s 0us/step
Downloading data from https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite
286720/284398 [==============================] - 0s 0us/step
294912/284398 [===============================] - 0s 0us/step

ประมวลผลอินพุตล่วงหน้า

  • รูปภาพเนื้อหาและรูปภาพสไตล์ต้องเป็นรูปภาพ RGB โดยมีค่าพิกเซลเป็นตัวเลข float32 ระหว่าง [0..1]
  • ขนาดรูปภาพสไตล์ต้องเป็น (1, 256, 256, 3) เราครอบตัดรูปภาพจากศูนย์กลางและปรับขนาด
  • รูปภาพเนื้อหาต้องเป็น (1, 384, 384, 3) เราครอบตัดรูปภาพจากศูนย์กลางและปรับขนาด
# Function to load an image from a file, and add a batch dimension.
def load_img(path_to_img):
  img = tf.io.read_file(path_to_img)
  img = tf.io.decode_image(img, channels=3)
  img = tf.image.convert_image_dtype(img, tf.float32)
  img = img[tf.newaxis, :]

  return img

# Function to pre-process by resizing an central cropping it.
def preprocess_image(image, target_dim):
  # Resize the image so that the shorter dimension becomes 256px.
  shape = tf.cast(tf.shape(image)[1:-1], tf.float32)
  short_dim = min(shape)
  scale = target_dim / short_dim
  new_shape = tf.cast(shape * scale, tf.int32)
  image = tf.image.resize(image, new_shape)

  # Central crop the image.
  image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)

  return image

# Load the input images.
content_image = load_img(content_path)
style_image = load_img(style_path)

# Preprocess the input images.
preprocessed_content_image = preprocess_image(content_image, 384)
preprocessed_style_image = preprocess_image(style_image, 256)

print('Style Image Shape:', preprocessed_style_image.shape)
print('Content Image Shape:', preprocessed_content_image.shape)
Style Image Shape: (1, 256, 256, 3)
Content Image Shape: (1, 384, 384, 3)

เห็นภาพอินพุต

def imshow(image, title=None):
  if len(image.shape) > 3:
    image = tf.squeeze(image, axis=0)

  plt.imshow(image)
  if title:
    plt.title(title)

plt.subplot(1, 2, 1)
imshow(preprocessed_content_image, 'Content Image')

plt.subplot(1, 2, 2)
imshow(preprocessed_style_image, 'Style Image')

png

เรียกใช้การถ่ายโอนสไตล์ด้วย TensorFlow Lite

ทำนายสไตล์

# Function to run style prediction on preprocessed style image.
def run_style_predict(preprocessed_style_image):
  # Load the model.
  interpreter = tf.lite.Interpreter(model_path=style_predict_path)

  # Set model input.
  interpreter.allocate_tensors()
  input_details = interpreter.get_input_details()
  interpreter.set_tensor(input_details[0]["index"], preprocessed_style_image)

  # Calculate style bottleneck.
  interpreter.invoke()
  style_bottleneck = interpreter.tensor(
      interpreter.get_output_details()[0]["index"]
      )()

  return style_bottleneck

# Calculate style bottleneck for the preprocessed style image.
style_bottleneck = run_style_predict(preprocessed_style_image)
print('Style Bottleneck Shape:', style_bottleneck.shape)
Style Bottleneck Shape: (1, 1, 1, 100)

การแปลงสไตล์

# Run style transform on preprocessed style image
def run_style_transform(style_bottleneck, preprocessed_content_image):
  # Load the model.
  interpreter = tf.lite.Interpreter(model_path=style_transform_path)

  # Set model input.
  input_details = interpreter.get_input_details()
  interpreter.allocate_tensors()

  # Set model inputs.
  interpreter.set_tensor(input_details[0]["index"], preprocessed_content_image)
  interpreter.set_tensor(input_details[1]["index"], style_bottleneck)
  interpreter.invoke()

  # Transform content image.
  stylized_image = interpreter.tensor(
      interpreter.get_output_details()[0]["index"]
      )()

  return stylized_image

# Stylize the content image using the style bottleneck.
stylized_image = run_style_transform(style_bottleneck, preprocessed_content_image)

# Visualize the output.
imshow(stylized_image, 'Stylized Image')

png

การผสมผสานสไตล์

เราสามารถผสมผสานสไตล์ของรูปภาพเนื้อหาเข้ากับเอาต์พุตที่มีสไตล์ ซึ่งจะทำให้เอาต์พุตดูเหมือนรูปภาพเนื้อหามากขึ้น

# Calculate style bottleneck of the content image.
style_bottleneck_content = run_style_predict(
    preprocess_image(content_image, 256)
    )
# Define content blending ratio between [0..1].
# 0.0: 0% style extracts from content image.
# 1.0: 100% style extracted from content image.
content_blending_ratio = 0.5

# Blend the style bottleneck of style image and content image
style_bottleneck_blended = content_blending_ratio * style_bottleneck_content \
                           + (1 - content_blending_ratio) * style_bottleneck

# Stylize the content image using the style bottleneck.
stylized_image_blended = run_style_transform(style_bottleneck_blended,
                                             preprocessed_content_image)

# Visualize the output.
imshow(stylized_image_blended, 'Blended Stylized Image')

png

เกณฑ์มาตรฐานประสิทธิภาพ

หมายเลขมาตรฐานประสิทธิภาพได้รับการสร้างขึ้นด้วยเครื่องมือ อธิบายไว้ที่นี่

ชื่อรุ่น ขนาดรุ่น อุปกรณ์ นภาภรณ์ ซีพียู GPU
รูปแบบการทำนายรูปแบบ (int8) 2.8 Mb พิกเซล 3 (แอนดรอยด์ 10) 142ms 14ms
พิกเซล 4 (แอนดรอยด์ 10) 5.2ms 6.7ms
iPhone XS (iOS 12.4.1) 10.7ms
รูปแบบการแปลงรูปแบบ (int8) 0.2 Mb พิกเซล 3 (แอนดรอยด์ 10) 540ms
พิกเซล 4 (แอนดรอยด์ 10) 405ms
iPhone XS (iOS 12.4.1) 251ms
รูปแบบการทำนายลักษณะ (float16) 4.7 Mb พิกเซล 3 (แอนดรอยด์ 10) 86ms 28ms 9.1ms
พิกเซล 4 (แอนดรอยด์ 10) 32ms 12ms 10ms
รูปแบบการถ่ายโอนสไตล์ (float16) 0.4 Mb พิกเซล 3 (แอนดรอยด์ 10) 1095ms 545ms 42ms
พิกเซล 4 (แอนดรอยด์ 10) 603ms 377ms 42ms

* ใช้ 4 เธรด
** 2 เธรดบน iPhone เพื่อประสิทธิภาพที่ดีที่สุด