2
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

1
  • with numpy you can numpy.array(pix) and with cv2 you can cv2.imwrite your array as an image Commented Feb 17, 2020 at 15:27

3 Answers 3

4

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, ...).

Sign up to request clarification or add additional context in comments.

4 Comments

This is not the image you will get from the OP's data! It should be orange-coloured where you have blue. PIL uses RGB ordering and you have re-ordered the OP's data into BGR ordering!
Well seen. Edited. Thanks!
How to change it into RGB ordering? @MarkSetchell
@GedePawitradi It depends on what you are planning to do next, and your question is very vague. I don't even know what ordering your original data was in... nor if you plan to process it using PIL or OpenCV/Numpy. Please click edit under your question and improve it so I (and others) can assist you better. Thanks.
1

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()

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.