Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to draw an image from discrete pixel values in Python?

I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it.

Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time.

I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format.

I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?

like image 748
saffsd Avatar asked Jan 12 '09 06:01

saffsd


People also ask

How do I get the pixel value of an image in OpenCV?

Figure 5: In OpenCV, pixels are accessed by their (x, y)-coordinates. The origin, (0, 0), is located at the top-left of the image. OpenCV images are zero-indexed, where the x-values go left-to-right (column number) and y-values go top-to-bottom (row number). Here, we have the letter “I” on a piece of graph paper.


1 Answers

If you have numpy and scipy available (and if you are manipulating large arrays in Python, I would recommend them), then the scipy.misc.pilutil.toimage function is very handy. A simple example:

import numpy as np import scipy.misc as smp  # Create a 1024x1024x3 array of 8 bit unsigned integers data = np.zeros( (1024,1024,3), dtype=np.uint8 )  data[512,512] = [254,0,0]       # Makes the middle pixel red data[512,513] = [0,0,255]       # Makes the next pixel blue  img = smp.toimage( data )       # Create a PIL image img.show()                      # View in default viewer 

The nice thing is toimage copes with different data types very well, so a 2D array of floating-point numbers gets sensibly converted to grayscale etc.

You can download numpy and scipy from here. Or using pip:

pip install numpy scipy 
like image 179
BADC0DE Avatar answered Oct 03 '22 23:10

BADC0DE