نقل الأسلوب الفني باستخدام TensorFlow Lite

عرض على TensorFlow.org تشغيل في Google Colab عرض المصدر على جيثب تحميل دفتر انظر نموذج TF Hub

واحدة من أكثر التطورات إثارة في التعلم العميق ليخرج في الآونة الأخيرة هو نقل الفني أسلوب ، أو القدرة على خلق صورة جديدة، والمعروفة باسم لحن ، استنادا إلى صورتين المدخلات: واحد يمثل أسلوب فني واحد يمثل المحتوى.

مثال على نقل النمط

باستخدام هذه التقنية ، يمكننا إنشاء أعمال فنية جديدة جميلة في مجموعة من الأساليب.

مثال على نقل النمط

إذا كنت مستخدمًا جديدًا لـ TensorFlow Lite وتعمل بنظام Android ، فإننا نوصي باستكشاف أمثلة التطبيقات التالية التي يمكن أن تساعدك على البدء.

الروبوت سبيل المثال دائرة الرقابة الداخلية سبيل المثال

إذا كنت تستخدم نظام أساسي بخلاف نظام Android أو iOS، أو كنت على دراية بالفعل لايت واجهات برمجة التطبيقات TensorFlow ، يمكنك اتباع هذا البرنامج التعليمي لمعرفة كيفية تطبيق نقل أسلوب على أي زوج من محتوى وصورة الاسلوب مع المدربين قبل TensorFlow لايت نموذج. يمكنك استخدام النموذج لإضافة نقل النمط إلى تطبيقات الهاتف المحمول الخاصة بك.

هذا النموذج هو مفتوح المصدر على جيثب . يمكنك إعادة تدريب النموذج بمعلمات مختلفة (على سبيل المثال ، زيادة أوزان طبقات المحتوى لجعل الصورة الناتجة تبدو أكثر شبهاً بصورة المحتوى).

فهم بنية النموذج

نموذج معماري

يتكون نموذج النقل الفني هذا من نموذجين فرعيين:

  1. أسلوب Prediciton نموذج A الشبكة العصبية التي تأخذ صورة أسلوب الإدخال إلى 100 البعد ناقلات أسلوب عنق الزجاجة MobilenetV2 القائم.
  2. أسلوب تحويل نموذج 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')

بي إن جي

قم بتشغيل نقل النمط باستخدام 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')

بي إن جي

مزج الأسلوب

يمكننا دمج نمط صورة المحتوى في الإخراج المنمق ، والذي بدوره يجعل الإخراج يبدو أشبه بصورة المحتوى.

# 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')

بي إن جي

معايير الأداء

يتم إنشاؤها أرقام مؤشر الأداء مع أداة الموصوفة هنا .

اسم النموذج حجم النموذج جهاز NNAPI وحدة المعالجة المركزية GPU
نموذج تنبؤ النمط (int8) 2.8 ميغا بايت Pixel 3 (Android 10) 142 مللي ثانية 14 مللي ثانية
Pixel 4 (Android 10) 5.2 مللي ثانية 6.7 مللي ثانية
iPhone XS (iOS 12.4.1) 10.7 مللي ثانية
نموذج تحويل النمط (int8) 0.2 ميغا بايت Pixel 3 (Android 10) 540 مللي ثانية
Pixel 4 (Android 10) 405 مللي ثانية
iPhone XS (iOS 12.4.1) 251 مللي ثانية
نموذج تنبؤ النمط (float16) 4.7 ميغا بايت Pixel 3 (Android 10) 86 مللي ثانية 28 مللي ثانية 9.1 مللي ثانية
Pixel 4 (Android 10) 32 مللي ثانية 12 مللي ثانية 10 مللي ثانية
نموذج نقل النمط (float16) 0.4 ميغا بايت Pixel 3 (Android 10) 1095 مللي ثانية 545 مللي ثانية 42 مللي ثانية
Pixel 4 (Android 10) 603 مللي ثانية 377 مللي ثانية 42 مللي ثانية

* 4 خيوط مستخدمة.
** خيطان على iPhone للحصول على أفضل أداء.