使用PIL和putdata()绘制像素数据

时间:2013-06-10 22:35:41

标签: python python-imaging-library

我正在尝试为图像绘制一系列像素,并假设使用putdata()比使用putpixel()绘制每个像素要快得多。

下面的代码段确实有效,但正如预期的那样缓慢。我现在正试图将所有的像素和颜色值都放到一个我可以使用putdata()的序列对象中,但对python来说还是比较新的,并努力以正确的顺序获取像素坐标和rgb颜色。

谢谢,

对于我们遍历的每个像素,它从图中查找'密度'(由x coord然后y列出)并将其与颜色中的rgb值相匹配,它基本上绘制了彩色散点图。

    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")

1 个答案:

答案 0 :(得分:1)

一些循环优化:

# 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)))

此外,将colours更改为简单列表(数组)。避免使用dicts,因为查找速度较慢。