Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an image in PIL using a list of RGB tuples?

Suppose I have a list of pixels (represented as tuples with 3 RGB values) in a list that looks like list(im.getdata()), like this:

[(0,0,0),(255,255,255),(38,29,58)...] 

How do I create a new image using RGB values (each tuple corresponds to a pixel) in this format?

Thanks for your help.

like image 962
Amit Avatar asked Aug 21 '12 20:08

Amit


People also ask

How do I create a new image in PIL?

new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band).

Does PIL use RGB or BGR?

But for PIL, the input is RGB, while it's BGR for cv2.

How do I import a picture into PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).


2 Answers

You can do it like this:

list_of_pixels = list(im.getdata()) # Do something to the pixels... im2 = Image.new(im.mode, im.size) im2.putdata(list_of_pixels) 
like image 56
Aleksi Torhamo Avatar answered Oct 07 '22 18:10

Aleksi Torhamo


You can also use scipy for that:

#!/usr/bin/env python  import scipy.misc import numpy as np  # Image size width = 640 height = 480 channels = 3  # Create an empty image img = np.zeros((height, width, channels), dtype=np.uint8)  # Draw something (http://stackoverflow.com/a/10032271/562769) xx, yy = np.mgrid[:height, :width] circle = (xx - 100) ** 2 + (yy - 100) ** 2  # Set the RGB values for y in range(img.shape[0]):     for x in range(img.shape[1]):         r, g, b = circle[y][x], circle[y][x], circle[y][x]         img[y][x][0] = r         img[y][x][1] = g         img[y][x][2] = b  # Display the image scipy.misc.imshow(img)  # Save the image scipy.misc.imsave("image.png", img) 

gives

enter image description here

like image 40
Martin Thoma Avatar answered Oct 07 '22 18:10

Martin Thoma