0

我正在尝试将一系列像素绘制到图像上,并且正在假设使用 putdata() 比使用 putpixel() 绘制每个单独的像素要快得多。

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

谢谢,

对于我们循环遍历的每个像素,它从绘图中查找“密度”(由 x 坐标然后 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")
4

1 回答 1

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为简单列表(数组)。避免使用字典,因为查找速度较慢。

于 2013-06-10T23:08:53.653 回答