保存相同的数据会生成不同的图像 - Python

时间:2013-11-21 23:14:41

标签: python image matplotlib save

我的代码中有两种保存图像数据的方法,一种是将其保存为灰度,另一种是生成热图图像:

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 / VariabilityOfGradients / ContourMap”)       ContourMap.generate_heat_map_image( “ImagesOutput / VariabilityOfGradients / ContourMapHeatMap”)

我将一张图像相对于另一张图像旋转。

方法1:

save_image

方法2:

generate_heat_map_image

我不明白为什么,但我必须解决这个问题。

任何帮助将不胜感激。 提前谢谢。

1 个答案:

答案 0 :(得分: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)并将其显示为MxN图像。