Same data saved generate different images - Python

百般思念 提交于 2019-12-11 19:49:23

问题


I have in my code two methods to save images data, one to just save it values in greyscale and another one to generate a heat map image:

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

The class that represents my data is this:

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)

Passing the same data for both methods

ContourMap.save_image("ImagesOutput/VariabilityOfGradients/ContourMap") ContourMap.generate_heat_map_image("ImagesOutput/VariabilityOfGradients/ContourMapHeatMap")

I get one image rotated in relation to the other.

Method 1:

Method 2:

I don't get it why, but I have to fix this.

Any help would be appreciated. Thanks in advance.


回答1:


Apparently the data are in row-major format, but you're iterating as if it were in column-major format, which rotates the whole thing by -90 degrees.

The quick fix is to replace this line:

color = self.data[x][y]

… with this one:

color = self.data[y][x]

(Although presumably data is an array, so you really ought to be using self.data[y, x] instead.)

A clearer fix is:

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

This may not be entirely clear from the pyplot documentation, but if you look at imshow, it explains that it takes an array-like object of shape (n, m) and displays it as an MxN image.



来源:https://stackoverflow.com/questions/20133904/same-data-saved-generate-different-images-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!