4242
4343import tensorflow as tf
4444
45+ from tensorflow .python .eager import context
46+
4547
4648def resize_by_area (img , size ):
4749 """image resize function used by quite a few image problems."""
@@ -463,6 +465,21 @@ def hparams(self, defaults, unused_model_hparams):
463465 p .target_space_id = 1
464466
465467
468+ def _encoded_images (images ):
469+ if context .in_eager_mode ():
470+ for image in images :
471+ yield tf .image .encode_png (image ).numpy ()
472+ else :
473+ (width , height , channels ) = images [0 ].shape
474+ with tf .Graph ().as_default ():
475+ image_t = tf .placeholder (dtype = tf .uint8 , shape = (width , height , channels ))
476+ encoded_image_t = tf .image .encode_png (image_t )
477+ with tf .Session () as sess :
478+ for image in images :
479+ enc_string = sess .run (encoded_image_t , feed_dict = {image_t : image })
480+ yield enc_string
481+
482+
466483def image_generator (images , labels ):
467484 """Generator for images that takes image and labels lists and creates pngs.
468485
@@ -484,20 +501,15 @@ def image_generator(images, labels):
484501 """
485502 if not images :
486503 raise ValueError ("Must provide some images for the generator." )
487- (width , height , channels ) = images [0 ].shape
488- with tf .Graph ().as_default ():
489- image_t = tf .placeholder (dtype = tf .uint8 , shape = (width , height , channels ))
490- encoded_image_t = tf .image .encode_png (image_t )
491- with tf .Session () as sess :
492- for (image , label ) in zip (images , labels ):
493- enc_string = sess .run (encoded_image_t , feed_dict = {image_t : image })
494- yield {
495- "image/encoded" : [enc_string ],
496- "image/format" : ["png" ],
497- "image/class/label" : [int (label )],
498- "image/height" : [height ],
499- "image/width" : [width ]
500- }
504+ width , height , _ = images [0 ].shape
505+ for (enc_image , label ) in zip (_encoded_images (images ), labels ):
506+ yield {
507+ "image/encoded" : [enc_image ],
508+ "image/format" : ["png" ],
509+ "image/class/label" : [int (label )],
510+ "image/height" : [height ],
511+ "image/width" : [width ]
512+ }
501513
502514
503515# URLs and filenames for MNIST data.
0 commit comments