Loading Image with Keras

Erwin Mazwardi
2 min readMar 31, 2024

--

If you work with images in CNN for example, you must know how to read or load images using Python code. Keras provides a function called load_img.

from tensorflow.keras.preprocessing.image import load_img

Let’s try loading an image using the load_img function.

img = load_img('street.jpg')
img.show()

If you want to find out the image format, mode, and size, then you can use the following codes.

print(type(img))
print(img.format)
print(img.mode)
print(img.size)

The results are as follows.

<class 'PIL.JpegImagePlugin.JpegImageFile'>
JPEG
RGB
(400, 300)

It tells you that the current image format is JPEG. It has the type of RGB and the size of the image is 400 x 300 corresponding with the width and the height of the image.

The load_img creates a PIL object as shown previously. You cannot use this image object as a train input of a CNN model. The object has to be converted to an array of numbers using a Keras function called img_to_array.

from tensorflow.keras.preprocessing.image import img_to_array

Then use the following Python code to transform the PIL object to an array of numbers.

img_array = img_to_array(img)

If you want to find out what information resulted by the img_to_array function, then run the following codes.

print(img_array.shape)
print(img_array[0])
print(img_array.dtype)

The results are as follows. The array has a dimension of 300x400x3. The first pixel value of index 0 is [184. 206. 220.], which has the type of float32.

(300, 400, 3)
[[184. 206. 220.]
[229. 251. 255.]
[225. 247. 255.]
...
[131. 144. 124.]
[108. 117. 96.]
[104. 114. 90.]]
float32

Now you can perform any operation on the array for example normalizing the values of the array using the following codes.

normalize_img_array = img_array/255.0
print(normalize_img_array[0][0])

The result is shown below.

[0.72156864 0.80784315 0.8627451 ]

This new RGB values of [0.72156864 0.80784315 0.8627451 ] correspond to the original values of [184. 206. 220.].

--

--

Erwin Mazwardi

Master of Data Science. A data scientist and IC verification engineer.