我分离了彩色图像的 3 个 channel 。我创建了一个与图像大小相同的新 NumPy 数组,并将图像的 3 个 channel 存储到 3D NumPy 数组的 3 个切片中。绘制 NumPy 数组后,绘制的图像与原始图像不同。为什么会发生这种情况?
img
和 new_img
数组具有相同的元素,但图像不同。
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
img=mpimg.imread('/storage/emulated/0/1sumint/kali5.jpg')
new_img=np.empty(img.shape)
new_img[:,:,0]=img[:,:,0]
new_img[:,:,1]=img[:,:,1]
new_img[:,:,2]=img[:,:,2]
plt.imshow(new_img)
plt.show()
期望图像与原始图像相同。
最佳答案
问题是您的新图像将使用此行的默认数据类型 float64
创建:
new_img=np.empty(img.shape)
除非您指定不同的dtype
。
您可以(最好)复制原始图像的dtype
,如下所示:
new_img = np.empty(im.shape, dtype=img.dtype)
或者使用这样的东西:
new_img = np.zeros_like(im)
或者(最差)指定一个您碰巧知道的与您的数据匹配的数据,如下所示,
new_img = np.empty(im.shape, dtype=np.uint8)
我认为您有某种原因一次复制一个 channel ,但如果没有,您可以避免上述所有问题,只需执行以下操作即可:
new_img = np.copy(img)
关于matplotlib - 对图像的 channel 进行切片并将 channel 存储到 numpy 数组中(与图像大小相同)。绘制 numpy 数组而不给出原始图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57097223/