简体   繁体   中英

Plotting pixel data using PIL and putdata()

I'm trying to plot a series of pixels to an image, and am working off the assumption that using putdata() is a supremely quicker than plotting each individual pixel with putpixel().

The snippet below does work but as expected is slow. I'm now trying to get all the pixel and colour values into a sequence object that I can use putdata() with, but am fairly new to python and struggling to get the pixel coordinates and rgb colours in the correct orders.

Thanks,

For each pixel we loop through it looks up the 'density' from plots (listed by x coord then y) and matches this against an rgb value in colours, its basically plotting a colourful scatter graph.

    plots = {800: {2400: 2, 1900: 2, 2000: 4, 2100: 5, 2200: 2, 2300: 1}, 1200: {2100: 1}, 900: {2100: 1, 1900: 1}, 1000: {2600: 1, 2100: 1, 1900: 1}, 300: {2000: 2, 2200: 2, 1200: 1, 2100: 1, 2500: 1}, 1100: {2000: 2, 2500: 1, 1900: 1}, 400: {2500: 1, 1800: 5, 1900: 4, 2000: 2, 2600: 1, 2200: 1}, 200: {2000: 1, 2600: 2, 2700: 2, 2500: 1}, 1300: {2000: 2}, 600: {2800: 2, 1800: 5, 1900: 2, 2000: 3, 2100: 5, 2200: 2}, 500: {2400: 6, 2500: 2, 2600: 1, 1900: 6, 2700: 1, 2000: 4, 2100: 2, 2300: 5}, 700: {2000: 9, 1900: 5, 2100: 2, 2800: 1, 1800: 7}}

image = Image.new('RGB', imgsize, rgbcolour)

    # Set colour values for each density
    colours = {0:rgbcolour,1:(125, 60, 218),2:(234, 163, 240),3:(66, 74, 145),4:(59, 165, 227),5:(0, 175, 89),6:(74, 224, 194),7:(255, 230, 66),8:(246, 148, 55),9:(255, 58, 239),10:(243, 36, 62)}

    # Loop through all pixels and plot them
    for x in xrange(roundup(column_stats['f2'][MAX])):
        for y in xrange(roundup(column_stats['f1'][MAX])):
            x_plot = int(round(float(x),-2))
            y_plot = int(round(float(y),-2))
            if x_plot in plots:
                if y_plot in plots[x_plot]:
                    image.putpixel((x,y),colours.get(plots[x_plot][y_plot], (243, 36, 62)))

image.save(name+'.png', "PNG")

Some loop optimization:

# Loop through all pixels and plot them
x_max = roundup(column_stats['f2'][MAX])
y_max = roundup(column_stats['f1'][MAX])
for x in xrange(x_max):
    x_plot = int(round(float(x),-2))
    if x_plot in plots:
        plots_x = plots[x_plot]
        for y in xrange(y_max):
            y_plot = int(round(float(y),-2))
            if y_plot in plots_x:
                image.putpixel((x,y),colours.get(plots_x[y_plot], (243, 36, 62)))

Also, change colours to a simple list (array). Avoid dicts because lookups are slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM