保存相同的数据会生成不同的图像 - Python [英] Same data saved generate different images - Python
问题描述
我的代码中有两种保存图像数据的方法,一种是将其保存为灰度值,另一种是生成热图图像:
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()
代表我数据的类是:
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)
ContourMap.save_image("ImagesOutput/VariabilityOfGradients/ContourMap") ContourMap.generate_heat_map_image("ImagesOutput/VariabilityOfGradients/ContourMapHeatMap")
我得到一个图像相对于另一个旋转。
I get one image rotated in relation to the other.
方法1:
方法2:
我不明白为什么,但我必须解决这个问题。
I don't get it why, but I have to fix this.
任何帮助不胜感激。
提前谢谢。
Any help would be appreciated. Thanks in advance.
推荐答案
显然数据是行主格式,但你正在迭代,好像在迭代它采用列式主格式,将整个事物旋转-90度。
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]
...这一个:
color = self.data[y][x]
(虽然大概是数据
是一个数组,所以你真的应该改为使用 self.data [y,x]
。)
(Although presumably data
is an array, so you really ought to be using self.data[y, x]
instead.)
更明确的解决方法是:
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))
这可能不是完全是cl来自pyplot文档,但如果你看一下 imshow
,它解释了它需要一个类似于数组的形状对象(n,m)并将其显示为MxN图像。
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.
这篇关于保存相同的数据会生成不同的图像 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!