Как создать файл модели.pb для передачи произвольного стиля
Произвольная стилизация изображения предоставляет метод для стилизации любого изображения желаемого стиля. https://github.com/tensorflow/magenta/tree/master/magenta/models/arbitrary_image_stylization
Поэтому моя идея - преобразовать файл модели.ckpt в файл.pb и использовать этот файл pb в приложении Android.
Для преобразования.ckpt в файл.pb.txt используется следующий код:
_def main(unused_argv=None):
with tf.Graph().as_default(), tf.Session() as sess:
# Defines place holder for the style image.
style_img_ph = tf.placeholder(tf.float32, shape=[None, None, 3], name="style_img_ph")
style_img_preprocessed = image_utils.resize_image(style_img_ph, 256)
# Defines place holder for the content image.
content_img_ph = tf.placeholder(tf.float32, shape=[None, None, 3], name="content_img_ph")
content_img_preprocessed = image_utils.resize_image(content_img_ph, 256)
# Defines the model.
stylized_images, _, _, bottleneck_feat = build_model.build_model(
content_img_preprocessed,
style_img_preprocessed,
trainable=False,
is_training=False,
inception_end_point='Mixed_6e',
style_prediction_bottleneck=100,
adds_losses=False)
if tf.gfile.IsDirectory(FLAGS.checkpoint):
checkpoint = tf.train.latest_checkpoint(FLAGS.checkpoint)
else:
checkpoint = FLAGS.checkpoint
tf.logging.info('loading latest checkpoint file: {}'.format(checkpoint))
init_fn = slim.assign_from_checkpoint_fn(checkpoint,
slim.get_variables_to_restore())
sess.run([tf.local_variables_initializer()])
init_fn(sess)
# Gets list of input content images.
content_img_np = image_utils.load_np_image_uint8(FLAGS.content_img_path)[:, :, : 3]
style_img_np = image_utils.load_np_image_uint8(FLAGS.style_img_path)[:, :, : 3]
# Computes bottleneck features of the style prediction network for the
# identity transform.
identity_params = sess.run(bottleneck_feat, feed_dict={style_img_ph: content_img_np})
# Computes bottleneck features of the style prediction network for the
# given style image.
style_params = sess.run(bottleneck_feat, feed_dict={style_img_ph: style_img_np})
stylized_image_res = sess.run(stylized_images, feed_dict={
bottleneck_feat:
identity_params * (1 - 0.90) + style_params * 0.90,
content_img_ph:
content_img_np
}
)
# Saves stylized image.
image_utils.save_np_image(stylized_image_res,FLAGS.output_path)
tf.train.write_graph(sess.graph_def, "/Protobuf/", "style_graph.pb.txt", as_text=True)_
Это сгенерировало файл GraphDef style_graph.pb.txt
заморозить график, используемый скрипт, как показано ниже /style_frozen.pb
Этот сгенерированный файл style_frozen.pb
Однако при загрузке этого сгенерированного / заблокированного файла pb, как показано ниже
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(
graph_def,
input_map=None,
return_elements=None,
op_dict=None,
producer_op_list=None
)
return graph
graph = load_graph('Protobuf/style_frozen.pb')
дает следующую ошибку
ValueError: graph_def недопустим на узле u'save/Assign': тензор ввода'Conv/biases:0'Невозможно преобразовать тензор типа float32 во ввод типа float32_ref
- Как устранить эту ошибку?
- Как добавить новый заполнитель для ввода, стиля и выходного изображения и сгенерировать файл pb? Потому что.ckpt не имеет тензорных узлов для передачи изображений ввода, стиля и вывода
- Должны ли мы переподготовить и затем сгенерировать файл.pb с нужными тензорными узлами?