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.
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).
But for PIL, the input is RGB, while it's BGR for cv2.
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).
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With