Gede Pawitradi
Gede Pawitradi

Reputation: 29

How to convert pixels stored in a list into an image with python?

pix = [
    [[90, 94, 6], [126, 108, 24], [180, 116, 42], [166, 116, 46], [72, 94, 31]],
    [[101, 96, 14], [190, 165, 84], [202, 134, 63], [170, 115, 50], [40, 50, 0]],
    [[145, 125, 53], [150, 112, 40], [148, 73, 6], [156, 90, 31], [25, 11, 1]],
    [[133, 124, 57], [165, 142, 75], [195, 142, 77], [169, 120, 62], [82, 74, 28]],
    [[73, 105, 40], [56, 77, 10], [138, 135, 67], [97, 95, 34], [45, 69, 21]],
]

I have a bunch of pixels stored in the list and now I want to convert it to an image. How can I turn that list into an image? Thank you

Upvotes: 2

Views: 586

Answers (3)

arnaud
arnaud

Reputation: 3473

Using PIL, you can create an image using an array:

from PIL import Image
import numpy as np
img = Image.fromarray(np.array(pix).astype(np.uint8))

Now, you may look at the image:

img.show()

enter image description here

Good thing is, from now on, you can benefit from all of PIL's toolcase for image processing (resize, thumbnail, filters, ...).

Upvotes: 4

nathancy
nathancy

Reputation: 46600

Here's how to do it using OpenCV. By default, OpenCV uses Numpy arrays to display images so you can simply convert the list into a <class 'numpy.ndarray'>.

Result:

import numpy as np
import cv2

pix = [
    [[90, 94, 6], [126, 108, 24], [180, 116, 42], [166, 116, 46], [72, 94, 31]],
    [[101, 96, 14], [190, 165, 84], [202, 134, 63], [170, 115, 50], [40, 50, 0]],
    [[145, 125, 53], [150, 112, 40], [148, 73, 6], [156, 90, 31], [25, 11, 1]],
    [[133, 124, 57], [165, 142, 75], [195, 142, 77], [169, 120, 62], [82, 74, 28]],
    [[73, 105, 40], [56, 77, 10], [138, 135, 67], [97, 95, 34], [45, 69, 21]],
]

# Convert to ndarray
img = np.array(pix).astype(np.uint8)

# Save image
cv2.imwrite('img.png', img)

# Display image
cv2.imshow('img', img)
cv2.waitKey()

Upvotes: 1

Nicolas Gervais
Nicolas Gervais

Reputation: 36624

The answer above transforms your list into a PIL Image. If you just want to see the image, you can do this:

import matplotlib.pyplot as plt

plt.imshow(pix)

Upvotes: 0

Related Questions