Python 中组合 R、G 和 B 分量时的颜色不匹配
Color mismatch in combining R,G, and B components in Python
在下面的代码中,我首先将图像转换为 Numpy 数组:
import numpy as np
from PIL import Image
sceneImage = Image.open('peppers.tif')
arrImage = np.array(sceneImage) # 256x256x3 array
现在我定义一个新的数组,按照下面的代码把arrImage
放在里面:
import matplotlib.pyplot as plt
final_image = np.zeros((N,N,3))
final_image[...,0] = arrImage[...,0]
final_image[...,1] = arrImage[...,1]
final_image[...,2] = arrImage[...,2]
plt.imshow(final_image)
plt.show()
换句话说,我分别复制粘贴了 R、G 和 B 组件(虽然这可以更容易地完成,但我是故意这样做的)。
现在,问题是 fianl_image
和 arrImage
没有向我显示相同的图像。形状如下所示:
arrImage:
final_image:
这两个不一样的问题是什么?
来自docs
dtype : 数据类型,可选
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
您只需要将正确的 dtype 传递给 np.zeros
即 np.uint8
:
sceneImage = Image.open('peppers.tif')
arrImage = np.array(sceneImage) # 256x256x3 array
final_image = np.zeros((N, N, 3),dtype=np.uint8)
final_image[..., 0] = arrImage[..., 0]
final_image[..., 1] = arrImage[..., 1]
final_image[..., 2] = arrImage[..., 2]
img = Image.fromarray(final_image, 'RGB')
img.save('whatever.png')
在下面的代码中,我首先将图像转换为 Numpy 数组:
import numpy as np
from PIL import Image
sceneImage = Image.open('peppers.tif')
arrImage = np.array(sceneImage) # 256x256x3 array
现在我定义一个新的数组,按照下面的代码把arrImage
放在里面:
import matplotlib.pyplot as plt
final_image = np.zeros((N,N,3))
final_image[...,0] = arrImage[...,0]
final_image[...,1] = arrImage[...,1]
final_image[...,2] = arrImage[...,2]
plt.imshow(final_image)
plt.show()
换句话说,我分别复制粘贴了 R、G 和 B 组件(虽然这可以更容易地完成,但我是故意这样做的)。
现在,问题是 fianl_image
和 arrImage
没有向我显示相同的图像。形状如下所示:
arrImage:
final_image:
这两个不一样的问题是什么?
来自docs
dtype : 数据类型,可选
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
您只需要将正确的 dtype 传递给 np.zeros
即 np.uint8
:
sceneImage = Image.open('peppers.tif')
arrImage = np.array(sceneImage) # 256x256x3 array
final_image = np.zeros((N, N, 3),dtype=np.uint8)
final_image[..., 0] = arrImage[..., 0]
final_image[..., 1] = arrImage[..., 1]
final_image[..., 2] = arrImage[..., 2]
img = Image.fromarray(final_image, 'RGB')
img.save('whatever.png')