abhisekp
abhisekp

Reputation: 5682

How to convert an array of numbers to bitmap image in python?

How do I convert a list of 1D numbers to a bitmap image?

I tried the following but it seems it doesn't quite work.

from PIL import Image

def get_img():
  img = Image.new('RGB', (255,255), "black") # Create a new black image
  pixels = img.load() # Create the pixel map
  width, height = img.size
  for i in range(width):    # For every pixel:
    for j in range(height):
      pixels[i,j] = (i, j, 100) # Set the colour accordingly
  return pixels

display(get_img()) # <PixelAccess at 0x7fca63ded7d0>

Upvotes: 0

Views: 2169

Answers (2)

azelcer
azelcer

Reputation: 1533

PIL.Image has a function that takes a numpy array and converts it to an image: Image.from_array. You can use it to generate B&W, grayscale, RGB or RGBA images easily.

In you case, the cleanest way to build the image is:

import numpy as np
from PIL import Image

def get_img(width=255, height=255):
    data = np.arange(width * height, dtype=np.int64).reshape((height, width))
    img_data = np.empty((height, width, 3), dtype=np.uint8)
    img_data[:, :, 0] = data // height
    img_data[:, :, 1] = data % width
    img_data[:, :, 2] = 100
    return Image.fromarray(img_data)

display(get_img())

Result:

Result image

Note that although this way of building the data needs to go through the array 3 times, it is still faster than plain-python loops. For the default values of 255 by 255 images, it is almost 30 times faster.

Upvotes: 1

pedro_bb7
pedro_bb7

Reputation: 2091

from PIL import Image
from IPython.display import display

img = Image.new('RGB', (255,255), "black") # Create a new black image
list_of_pixels = list(img.getdata())
print(list_of_pixels)
im2 = Image.new(img.mode, img.size)
im2.putdata(list_of_pixels)

display(im2)

Upvotes: 0

Related Questions