encoder.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 os
  25. import numpy as np
  26. import tensorflow as tf
  27. tf.flags.DEFINE_string('input_image', None, 'Location of input image. We rely '
  28. 'on tf.image to decode the image, so only PNG and JPEG '
  29. 'formats are currently supported.')
  30. tf.flags.DEFINE_integer('iteration', 15, 'Quality level for encoding image. '
  31. 'Must be between 0 and 15 inclusive.')
  32. tf.flags.DEFINE_string('output_codes', None, 'File to save output encoding.')
  33. tf.flags.DEFINE_string('model', None, 'Location of compression model.')
  34. FLAGS = tf.flags.FLAGS
  35. def get_output_tensor_names():
  36. name_list = ['GruBinarizer/SignBinarizer/Sign:0']
  37. for i in xrange(1, 16):
  38. name_list.append('GruBinarizer/SignBinarizer/Sign_{}:0'.format(i))
  39. return name_list
  40. def main(_):
  41. if (FLAGS.input_image is None or FLAGS.output_codes is None or
  42. FLAGS.model is None):
  43. print ('\nUsage: python encoder.py --input_image=/your/image/here.png '
  44. '--output_codes=output_codes.pkl --iteration=15 '
  45. '--model=residual_gru.pb\n\n')
  46. return
  47. if FLAGS.iteration < 0 or FLAGS.iteration > 15:
  48. print '\n--iteration must be between 0 and 15 inclusive.\n'
  49. return
  50. with tf.gfile.FastGFile(FLAGS.input_image) as input_image:
  51. input_image_str = input_image.read()
  52. with tf.Graph().as_default() as graph:
  53. # Load the inference model for encoding.
  54. with tf.gfile.FastGFile(FLAGS.model, 'rb') as model_file:
  55. graph_def = tf.GraphDef()
  56. graph_def.ParseFromString(model_file.read())
  57. _ = tf.import_graph_def(graph_def, name='')
  58. input_tensor = graph.get_tensor_by_name('Placeholder:0')
  59. outputs = [graph.get_tensor_by_name(name) for name in
  60. get_output_tensor_names()]
  61. input_image = tf.placeholder(tf.string)
  62. _, ext = os.path.splitext(FLAGS.input_image)
  63. if ext == '.png':
  64. decoded_image = tf.image.decode_png(input_image, channels=3)
  65. elif ext == '.jpeg' or ext == '.jpg':
  66. decoded_image = tf.image.decode_jpeg(input_image, channels=3)
  67. else:
  68. assert False, 'Unsupported file format {}'.format(ext)
  69. decoded_image = tf.expand_dims(decoded_image, 0)
  70. with tf.Session(graph=graph) as sess:
  71. img_array = sess.run(decoded_image, feed_dict={input_image:
  72. input_image_str})
  73. results = sess.run(outputs, feed_dict={input_tensor: img_array})
  74. results = results[0:FLAGS.iteration + 1]
  75. int_codes = np.asarray([x.astype(np.int8) for x in results])
  76. # Convert int codes to binary.
  77. int_codes = (int_codes + 1)/2
  78. export = np.packbits(int_codes.reshape(-1))
  79. with tf.gfile.FastGFile(FLAGS.output_codes, 'wb') as code_file:
  80. np.savez_compressed(code_file, shape=int_codes.shape, codes=export)
  81. if __name__ == '__main__':
  82. tf.app.run()