2013-11-21 202 views
0

我兩種方法來保存圖像數據,一個只是保存值在灰度和另一個產生熱圖的圖像在我的代碼:保存的相同數據生成不同的圖像 - 的Python

def save_image(self, name): 
    """ 
    Save an image data in PNG format 
    :param name: the name of the file 
    """ 
    graphic = Image.new("RGB", (self.width, self.height)) 
    putpixel = graphic.putpixel 
    for x in range(self.width): 
     for y in range(self.height): 
      color = self.data[x][y] 
      color = int(Utils.translate_range(color, self.range_min, self.range_max, 0, 255)) 
      putpixel((x, y), (color, color, color)) 
    graphic.save(name + ".png", "PNG") 

def generate_heat_map_image(self, name): 
    """ 
    Generate a heat map of the image 
    :param name: the name of the file 
    """ 
    #self.normalize_image_data() 
    plt.figure() 
    fig = plt.imshow(self.data, extent=[-1, 1, -1, 1]) 
    plt.colorbar(fig) 
    plt.savefig(name+".png") 
    plt.close() 

類代表我的數據是這樣的:

class ImageData: 
def __init__(self, width, height): 
    self.width = width 
    self.height = height 
    self.data = [] 
    for i in range(width): 
     self.data.append([0] * height) 

傳遞相同的數據這兩種方法

ContourMap.save_image(「ImagesOutput /瓦里亞bilityOfGradients/ContourMap 「) ContourMap.generate_heat_map_image(」 ImagesOutput/VariabilityOfGradients/ContourMapHeatMap「)

我得到相對於另一個圖像旋轉。

方法1:

save_image

方法2:

generate_heat_map_image

我不明白爲什麼,但我必須解決這個問題。

任何幫助,將不勝感激。 在此先感謝。

+1

作爲一個側面說明,爲什麼你首先使用['putpixel'](http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.putpixel) ?這是構建圖像最慢的方式,特別是在較舊的PIL/Pillow版本中。爲什麼不只是用一個矢量化操作來轉換數組,然後只是一次複製整個東西?或者使用'ImageDraw'?還是其他什麼? – abarnert

+0

我剛剛給了你兩個不同的提示,以及一個鏈接到文檔,其中有更廣泛的提示。 – abarnert

回答

1

顯然數據是以行爲主格式的,但是您正在迭代,就好像它是以列主格式一樣,它將整個事物旋轉-90度。

速戰速決是替換這一行:

color = self.data[x][y] 

...這一個:

color = self.data[y][x] 

(雖然可能data是一個數組,所以你真的應該使用self.data[y, x]代替。 )

更清楚的修復方法是:

for row in range(self.height): 
    for col in range(self.width): 
     color = self.data[row][col] 
     color = int(Utils.translate_range(color, self.range_min, self.range_max, 0, 255)) 
     putpixel((col, row), (color, color, color)) 

這可能不是從pyplot文檔完全清楚,但如果你看imshow,它解釋,它需要的形狀(N,M)的陣列狀物體並將其顯示爲一個M×N個圖像。

+0

所以我可以像這樣初始化我的數據:self.data = []我在範圍(高度):self.data.append([0] *寬度)來解決它?對不起,但我是Python新手。 – pceccon

+0

@pceccon:您是否試圖讓'imshow'版本旋轉以匹配您的'putpixel'版本,或者其他方式?如果'imshow'是正確的,保留你的數據,並改變你在'save_image'中循環的方式(如我的答案)。如果「ifshow」錯誤,請改變您構建數據的方式。 – abarnert

相關問題