tensorflow: InvalidArgumentError : Expected image (JPEG, PNG, or GIF), got unknown format starting with '255'

System information

  • OS Platform and Distribution :Linux Ubuntu 16.04
  • TensorFlow installed from :binary
  • TensorFlow version :1.1.0
  • Python version : 2.7.12

Describe the problem

trying to feed a model an image encoded in string as the model require that as an input string

signature_def {
  key: "serving_default"
  value {
    inputs {
      key: "image_bytes"
      value {
        name: "Placeholder:0"
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: -1
          }
        }
      }
    }
    inputs {
      key: "key"
      value {
        name: "Placeholder_1:0"
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: -1
          }
        }
      }
    }
    outputs {
      key: "key"
      value {
        name: "Identity:0"
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: -1
          }
        }
      }
    }
    outputs {
      key: "prediction"
      value {
        name: "ArgMax:0"
        dtype: DT_INT64
        tensor_shape {
          dim {
            size: -1
          }
        }
      }
    }
    outputs {
      key: "scores"
      value {
        name: "final_ops/softmax:0"
        dtype: DT_FLOAT
        tensor_shape {
          dim {
            size: -1
          }
          dim {
            size: 3
          }
        }
      }
    }
    method_name: "tensorflow/serving/predict"
  }
}

Here is the code :-

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="string" )
    return data

export_dir = '.'
with tf.Session(graph=tf.Graph()) as sess:
	model = tf.saved_model.loader.load(sess, ['serve'], export_dir)
	input_dict, output_dict =_signature_def_to_tensors(model.signature_def['serving_default'])
	out = sess.run(output_dict, feed_dict={input_dict['image_bytes']: load_image("fullsize.jpeg").flatten()})
	print(input_dict)

Error returns is :

InvalidArgumentError (see above for traceback): Expected image (JPEG, PNG, or GIF), got unknown format starting with '255'
	 [[Node: map/while/DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](map/while/TensorArrayReadV3)]]

how i can solve that , any help

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (2 by maintainers)

Most upvoted comments

This question is better asked on StackOverflow since it is not a bug or feature request. There is also a larger community that reads questions there. Thanks!

That said, a few things to note:

  • tf.image.decode_jpeg expects the encoded-JPEG bytes (i.e., the contents of the file). The use of PIL and in particular PIL.Image.load() suggests that the numpy array you’re creating consists of the decoded contents (decoded by PIL). Which is why the sess.run() call is failing as it expects an encoded JPEG but you’re providing it a decoded one.

  • To provide the raw contents of the file as a feed, you’d want to do something like so:

def load_image(filename):
  with open('fullsize.jpeg') as f:
    return np.array(f.read())

Which will create the numpy array of the encoded JPEG bytes that you can feed to your session.

Hope that helps.

@rohitkumar9989 you can solve this problem with the below code:

import cv2
import tensorflow as tf
import os

def check_images(s_dir, ext_list):
    bad_images=[]
    bad_ext=[]
    s_list= os.listdir(s_dir)
    for klass in s_list:
        klass_path=os.path.join (s_dir, klass)
        print ('processing class directory ', klass)
        if os.path.isdir(klass_path):
            file_list=os.listdir(klass_path)
            for f in file_list:               
                f_path=os.path.join (klass_path,f)
                index=f.rfind('.')
                ext=f[index+1:].lower()
                if ext not in ext_list:
                    print('file ', f_path, ' has an invalid extension ', ext)
                    bad_ext.append(f_path)
                if os.path.isfile(f_path):
                    try:
                        img=cv2.imread(f_path)
                        shape=img.shape
                        image_contents = tf.io.read_file(f_path)
                        image = tf.image.decode_jpeg(image_contents, channels=3)
                    except Exception as e:
                        print('file ', f_path, ' is not a valid image file')
                        print(e)
                        bad_images.append(f_path)
                else:
                    print('*** fatal error, you a sub directory ', f, ' in class directory ', klass)
        else:
            print ('*** WARNING*** you have files in ', s_dir, ' it should only contain sub directories')
    return bad_images, bad_ext

For execution of the above code:

source_dir =r'/data/validation/'
good_exts=['jpg','jpeg'] # list of acceptable extensions
bad_file_list, bad_ext_list=check_images(source_dir, good_exts)
if len(bad_file_list) !=0:
    print('improper image files are listed below')

print(bad_file_list)
print(bad_ext_list)

Awesome, thanks! Thanks for your handy help…

On Thu, 10 Jun 2021, 16:07 Deep Modi, @.***> wrote:

@rohitkumar9989 https://github.com/rohitkumar9989 Okay, That’s great. 😃

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tensorflow/tensorflow/issues/13583#issuecomment-858511996, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQS5W23LQD2EAC3XBJHOGQTTSCIX3ANCNFSM4D6KCJ6A .

@keyankarthisdk , maybe the reason is some picture is not the JPEG format. You can use tf.image.decode_jpeg() to test which picture is not the right format for tensorflow and then discard. I use this way solve the problem.