切片图像通道并将通道存储到 numpy 数组(与图像大小相同)。绘制 numpy 数组而不给出原始图像
Slicing the channels of image and storing the channels into numpy array(same size as image). Plotting the numpy array not giving the original image
我将彩色图像的 3 个通道分开。我创建了一个与图像大小相同的新 NumPy 数组,并将图像的 3 个通道存储到 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)
我假设您有某种原因需要一次复制一个频道,但如果没有,您可以避免上述所有问题,只需执行以下操作:
new_img = np.copy(img)
我将彩色图像的 3 个通道分开。我创建了一个与图像大小相同的新 NumPy 数组,并将图像的 3 个通道存储到 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)
我假设您有某种原因需要一次复制一个频道,但如果没有,您可以避免上述所有问题,只需执行以下操作:
new_img = np.copy(img)