python - Creating an image from a dictionary using PIL -


i have dictionary maps coordinate tuples (in range (0,0) (199, 199) grayscale values (integers between 0 , 255.) there way create pil image has specified values @ specified coordinates? i'd prefer solution uses pil 1 uses scipy.

as martineau suggests putpixel() ok when you're modifying few random pixels, it's not efficient building whole images. approach similar his, except use list of ints , .putdata(). here's code test these 3 different approaches.

from pil import image random import seed, randint  width, height = 200, 200 background = 0  seed(42) d = dict(((x, y), randint(0, 255)) x in range(width) y in range(height))  algorithm = 2 print('algorithm', algorithm)  if algorithm == 0:     im = image.new('l', (width, height))     in d:         im.putpixel(i, d[i]) elif algorithm == 1:     buff = bytearray((background _ in xrange(width * height)))     (x,y), v in d.items():         buff[y*width + x] = v     im = image.frombytes('l', (width,height), str(buff)) elif algorithm == 2:     data = [background] * width * height     in d:         x, y =         data[x + y * width] = d[i]     im = image.new('l', (width, height))     im.putdata(data)  #im.show()  fname = 'qrand%d.png' % algorithm im.save(fname) print(fname, 'saved') 

here typical timings on 2ghz machine running python 2.6.6

$ time ./qtest.py algorithm 0 qrand0.png saved  real    0m0.926s user    0m0.768s sys     0m0.040s  $ time ./qtest.py algorithm 1 qrand1.png saved  real    0m0.733s user    0m0.548s sys     0m0.020s  $ time ./qtest.py algorithm 2 qrand2.png saved  real    0m0.638s user    0m0.520s sys     0m0.032s 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -