Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Convert an Image to Numpy Array in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

import numpy as np
from PIL import Image, ImageOps, ImageStat
img = Image.open("../../home/media/poker/4h.png")
img
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=37x54 at 0x7F3DD95E9400>

You can use either numpy.asarray or numpy.array to convert an image to a numpy array. The resulting numpy array is a 3-dimensional array with the third/last dimention being the 3 channels (RGB) no matter the format of the image.

np.asarray(img)
array([[[ 37, 62, 59], [149, 174, 171], [225, 238, 239], ..., [232, 250, 249], [217, 235, 234], [122, 156, 154]], [[127, 133, 134], [240, 246, 247], [244, 243, 246], ..., [239, 240, 243], [243, 244, 247], [218, 233, 236]], [[152, 158, 159], [245, 251, 252], [237, 236, 239], ..., [235, 236, 239], [235, 236, 239], [227, 242, 245]], ..., [[ 45, 66, 64], [153, 174, 172], [233, 237, 239], ..., [235, 239, 241], [226, 230, 232], [132, 157, 152]], [[ 24, 45, 43], [ 38, 59, 57], [105, 109, 111], ..., [119, 123, 125], [ 92, 96, 98], [ 37, 62, 57]], [[ 25, 55, 50], [ 17, 47, 42], [ 15, 38, 33], ..., [ 16, 40, 40], [ 16, 40, 40], [ 19, 53, 49]]], dtype=uint8)
arr = np.array(img)
arr
array([[[ 37, 62, 59], [149, 174, 171], [225, 238, 239], ..., [232, 250, 249], [217, 235, 234], [122, 156, 154]], [[127, 133, 134], [240, 246, 247], [244, 243, 246], ..., [239, 240, 243], [243, 244, 247], [218, 233, 236]], [[152, 158, 159], [245, 251, 252], [237, 236, 239], ..., [235, 236, 239], [235, 236, 239], [227, 242, 245]], ..., [[ 45, 66, 64], [153, 174, 172], [233, 237, 239], ..., [235, 239, 241], [226, 230, 232], [132, 157, 152]], [[ 24, 45, 43], [ 38, 59, 57], [105, 109, 111], ..., [119, 123, 125], [ 92, 96, 98], [ 37, 62, 57]], [[ 25, 55, 50], [ 17, 47, 42], [ 15, 38, 33], ..., [ 16, 40, 40], [ 16, 40, 40], [ 19, 53, 49]]], dtype=uint8)

The resulting numpy array has the dimension (54, 37, 3) since the image has 3 channels (RGB).

arr.shape
(54, 37, 3)

Points in the middle of th red heart has large values in the first (R) channel, which is as expected.

arr[8, 8, :]
array([160, 0, 17], dtype=uint8)
arr[9, 9, :]
array([159, 0, 8], dtype=uint8)
arr[10, 10, :]
array([168, 0, 19], dtype=uint8)