Same data saved generate different images – Python
我的代码中有两种保存图像数据的方法,一种只是将其值保存为灰度值,另一种用于生成热图图像:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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): |
代表我的数据的类是这样的:
1
2 3 4 5 6 7 |
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”)
我得到一张相对于另一张旋转的图像。
方法一:
方法二:
我不明白为什么,但我必须解决这个问题。
任何帮助将不胜感激。
提前致谢。
- 作为旁注,您为什么首先使用 putpixel ?这是构建图像的最慢方法,尤其是在旧的 PIL/Pillow 版本中。为什么不用一个向量化操作来翻译数组,然后一次复制整个东西呢?还是使用 ImageDraw?或者只是别的什么?
- 我刚刚给了你两个不同的提示,以及一个文档链接,其中包含更广泛的提示。
显然数据是行优先格式,但您正在像列优先格式一样进行迭代,这会将整个数据旋转 -90 度。
快速解决方法是替换这一行:
1
|
color = self.data[x][y]
|
一个€|用这个:
1
|
color = self.data[y][x]
|
(虽然可能 data 是一个数组,所以你真的应该使用 self.data[y, x] 代替。)
更清晰的解决方法是:
1
2 3 4 5 |
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 图像。
- 所以我可以像这样初始化我的数据: self.data = [] for i in range(height): self.data.append([0] * width) 来修复它?抱歉,我是 Python 新手。
- @pceccon:您是要旋转 imshow 版本以匹配您的 putpixel 版本,还是相反?如果 imshow 是正确的,请不要理会您的数据,并更改在 save_image 中循环它的方式(如我的回答)。如果 ifshow 错误,请更改构建数据的方式。
来源:https://www.codenong.com/20133904/