encoder.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # ==============================================================================
  17. r"""Neural Network Image Compression Encoder.
  18. Compresses an image to a binarized numpy array. The image must be padded to a
  19. multiple of 32 pixels in height and width.
  20. Example usage:
  21. python encoder.py --input_image=/your/image/here.png \
  22. --output_codes=output_codes.pkl --iteration=15 --model=residual_gru.pb
  23. """
  24. import io
  25. import os
  26. import numpy as np
  27. import tensorflow as tf
  28. tf.flags.DEFINE_string('input_image', None, 'Location of input image. We rely '
  29. 'on tf.image to decode the image, so only PNG and JPEG '
  30. 'formats are currently supported.')
  31. tf.flags.DEFINE_integer('iteration', 15, 'Quality level for encoding image. '
  32. 'Must be between 0 and 15 inclusive.')
  33. tf.flags.DEFINE_string('output_codes', None, 'File to save output encoding.')
  34. tf.flags.DEFINE_string('model', None, 'Location of compression model.')
  35. FLAGS = tf.flags.FLAGS
  36. def get_output_tensor_names():
  37. name_list = ['GruBinarizer/SignBinarizer/Sign:0']
  38. for i in range(1, 16):
  39. name_list.append('GruBinarizer/SignBinarizer/Sign_{}:0'.format(i))
  40. return name_list
  41. def main(_):
  42. if (FLAGS.input_image is None or FLAGS.output_codes is None or
  43. FLAGS.model is None):
  44. print('\nUsage: python encoder.py --input_image=/your/image/here.png '
  45. '--output_codes=output_codes.pkl --iteration=15 '
  46. '--model=residual_gru.pb\n\n')
  47. return
  48. if FLAGS.iteration < 0 or FLAGS.iteration > 15:
  49. print('\n--iteration must be between 0 and 15 inclusive.\n')
  50. return
  51. with tf.gfile.FastGFile(FLAGS.input_image) as input_image:
  52. input_image_str = input_image.read()
  53. with tf.Graph().as_default() as graph:
  54. # Load the inference model for encoding.
  55. with tf.gfile.FastGFile(FLAGS.model, 'rb') as model_file:
  56. graph_def = tf.GraphDef()
  57. graph_def.ParseFromString(model_file.read())
  58. _ = tf.import_graph_def(graph_def, name='')
  59. input_tensor = graph.get_tensor_by_name('Placeholder:0')
  60. outputs = [graph.get_tensor_by_name(name) for name in
  61. get_output_tensor_names()]
  62. input_image = tf.placeholder(tf.string)
  63. _, ext = os.path.splitext(FLAGS.input_image)
  64. if ext == '.png':
  65. decoded_image = tf.image.decode_png(input_image, channels=3)
  66. elif ext == '.jpeg' or ext == '.jpg':
  67. decoded_image = tf.image.decode_jpeg(input_image, channels=3)
  68. else:
  69. assert False, 'Unsupported file format {}'.format(ext)
  70. decoded_image = tf.expand_dims(decoded_image, 0)
  71. with tf.Session(graph=graph) as sess:
  72. img_array = sess.run(decoded_image, feed_dict={input_image:
  73. input_image_str})
  74. results = sess.run(outputs, feed_dict={input_tensor: img_array})
  75. results = results[0:FLAGS.iteration + 1]
  76. int_codes = np.asarray([x.astype(np.int8) for x in results])
  77. # Convert int codes to binary.
  78. int_codes = (int_codes + 1)//2
  79. export = np.packbits(int_codes.reshape(-1))
  80. output = io.BytesIO()
  81. np.savez_compressed(output, shape=int_codes.shape, codes=export)
  82. with tf.gfile.FastGFile(FLAGS.output_codes, 'w') as code_file:
  83. code_file.write(output.getvalue())
  84. if __name__ == '__main__':
  85. tf.app.run()