TensorFlow | How to convert image to numpy array

This article explains how to convert image to Numpy array using TensorFlow. TensorFlow provides tf.keras.utils.img_to_array method to convert image instance to a Numpy array. Below is the code snippet to convert Image to Numpy array.

  • Download the image with tf.keras.utils.get_file
  •     
    import tensorflow as tf
    
    image_file = tf.keras.utils.get_file("flower.jpg",
        "https://storage.googleapis.com/gcptutorials.com/examples/flower.jpg")
        
    ====== Output ======
    Downloading data from https://storage.googleapis.com/gcptutorials.com/examples/flower.jpg
    229376/221594 [===============================] - 0s 0us/step
        
        
        

  • Load image with tf.keras.preprocessing.image.load_img
  •     
    img = tf.keras.preprocessing.image.load_img(image_file)
        
        

  • Convert image to numpy array with tf.keras.preprocessing.image.img_to_array
  •     
    image_array = tf.keras.preprocessing.image.img_to_array(img)
    print(image_array.shape)
    print(image_array)
        
    ======= Output ======
    (1297, 1920, 3)
    [[[124.  73.   7.]
        [126.  75.   9.]
        [128.  77.  11.]
        ...
        [ 66.  30.  34.]
        [ 69.  30.  35.]
        [ 69.  30.  35.]]
    
        [[125.  74.   8.]
        [127.  76.  10.]
        [129.  78.  12.]
        ...
        [ 66.  30.  34.]
        [ 67.  31.  35.]
        [ 70.  31.  36.]]
        ...
        [[125.  76.   9.]
        [126.  77.  10.]
        [128.  77.  11.]
        ...
        [ 67.  31.  35.]
        [ 68.  32.  36.]
        [ 69.  33.  37.]]]
        
        
        

  • Complete code for converting image to numpy array
  •     
    import tensorflow as tf
    
    image_file = tf.keras.utils.get_file("flower.jpg",
        "https://storage.googleapis.com/gcptutorials.com/examples/flower.jpg")
    img = tf.keras.preprocessing.image.load_img(image_file)
    
    image_array = tf.keras.preprocessing.image.img_to_array(img)
    print(image_array.shape)
    print(image_array)
        
        
        
        

    Follow US on Twitter: