我正在使用 Pillow 和 numpy,但在 Pillow Image 对象和 numpy 数组之间的转换存在问题。
当我执行以下代码时,结果很奇怪。
im = Image.open(os.path.join(self.img_path, ifname))
print im.size
in_data = np.asarray(im, dtype=np.uint8)
print in_data.shape
结果是
(1024, 768)
(768, 1024)
为什么维度变了?
我正在使用 Pillow 和 numpy,但在 Pillow Image 对象和 numpy 数组之间的转换存在问题。
当我执行以下代码时,结果很奇怪。
im = Image.open(os.path.join(self.img_path, ifname))
print im.size
in_data = np.asarray(im, dtype=np.uint8)
print in_data.shape
结果是
(1024, 768)
(768, 1024)
为什么维度变了?
我可能是列优先的,而 numpy 中的数组是行优先的
做in_data = in_data.T转置python数组
matplotlib可能应该用's检查 in_data 以imshow确保图片看起来正确。
但是您是否知道 matplotlib 带有自己的加载函数,可以直接为您提供 numpy 数组?见: http: //matplotlib.org/users/image_tutorial.html
如果您的图像是灰度的,请执行以下操作:
in_data = in_data.T
但是,如果您正在使用 rbg 图像,则要确保您的转置操作仅沿两个轴:
in_data = np.transpose(in_data, (1,0,2))
    实际上,这是因为与 numpy 数组相比,大多数图像库都会为您提供经过转置的图像。这是(我认为)因为您逐行编写图像文件,所以第一个索引(假设x)指的是行号(x垂直轴也是如此),第二个索引(y)指的是行中的后续像素(所以y是横轴),这违背了我们日常的坐标感。
如果你想正确处理它,你需要记住写:
image = library.LoadImage(path)
array = (library.FromImageToNumpyArray(image)).T
因此:
image = library.FromNumpyArrayToImage(array.T)
library.WriteImage(image, path)
这也适用于 3D 图像。但我不保证所有图像库都是这种情况 - 只是我使用的这些。