Image.fromarray更改大小 [英] Image.fromarray changes size

查看:489
本文介绍了Image.fromarray更改大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要存储到图像中的数据.我创建了一个宽度为100,高度为28的图像,我的矩阵具有相同的形状.当我使用Image.fromarray(matrix)时,形状会发生变化:

I have data that I want to store into an image. I created an image with width 100 and height 28, my matrix has the same shape. When I use Image.fromarray(matrix) the shape changes:

from PIL import Image

img = Image.new('L', (100, 28))
tmp = Image.fromarray(matrix)
print(matrix.shape) # (100, 28)
print(tmp.size) # (28, 100)
img.paste(tmp, (0, 0, 100, 28) # ValueError: images do not match

当我使用img.paste(tmp, (0, 0))时,会将对象粘贴到图像中,但是缺少以x值28开头的部分.

When I use img.paste(tmp, (0, 0)) the object is pasted into the image, but the part starting with the x value 28 is missing.

尺寸为什么会改变?

推荐答案

PIL和numpy具有不同的索引系统. matrix[a, b]为您提供x位置b和y位置a的点,但img.getpixel((a, b))为您提供x位置 a 和y位置 b 的点.结果,当您在numpy和PIL矩阵之间转换时,它们会切换其尺寸.要解决此问题,您可以对矩阵进行转置(matrix.transpose()).

这是正在发生的事情:

PIL and numpy have different indexing systems. matrix[a, b] gives you the point at x position b, and y position a, but img.getpixel((a, b)) gives you the point at x position a, and y position b. As a result of this, when you are converting between numpy and PIL matrices, they switch their dimensions. To fix this, you could take the transpose (matrix.transpose()) of the matrix.

Here's what's happening:

import numpy as np
from PIL import Image

img = Image.new('L', (100, 28))
img.putpixel((5, 3), 17)

matrix = np.array(img)

print matrix[5, 3] #This returns 0 

print matrix[3, 5] #This returns 17

matrix = matrix.transpose()
print matrix[5, 3] #This returns 17

print matrix[3, 5] #This returns 0

这篇关于Image.fromarray更改大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆