从 PIL 图像转换为 numpy 数组并将其转换回来后,图像的颜色正在改变
Colour of image is being changed after conversion from PIL image to numpy array and converting it back
这是我的代码
img = Image.open('./data/imgs/' + '0.jpg')
//converting to numpy array
img.load()
imgdata = np.asarray(img)
np.interp(imgdata, (imgdata.min(), imgdata.max()), (0, +1))
//converting back to PIL image
image = imgdata * 255
image = Image.fromarray(image.astype('uint8'), 'RGB')
image.show()
这是我的颜色失真输出
如何解决?
问题原因:
您没有使用 np.interp 的 return 值,因此 imgdata 不会被新值替换。因此它保留初始值范围 [0, 255] 并且它的 dtype 也是 np.uint8。当您执行 imgdata * 255 时,它无法满足 np.uint8 中的结果并且它溢出了(但是再次从 0 开始,因为它是无符号的)。
假设:
我假设您想将图像值从 [min(), max()] 映射到 [0, 1],然后通过将其乘以 255.
来重新缩放它。
解决方案:
如果我对您的代码的假设是正确的,请执行以下操作:
imgdata = np.interp(imgdata, (imgdata.min(), imgdata.max()), (0, +1))
else 从代码中删除 (* 255) 并将其更改为,
image = imgdata
您可以通过如下示例数组来测试此溢出:
sample = np.array([10, 20, 30], dtype=np.uint8)
sample2 = sample * 10
print(sample, sample2)
你会看到 sample2 的值是 [100, 200, 44] 而不是 [100, 200, 300]
这是我的代码
img = Image.open('./data/imgs/' + '0.jpg')
//converting to numpy array
img.load()
imgdata = np.asarray(img)
np.interp(imgdata, (imgdata.min(), imgdata.max()), (0, +1))
//converting back to PIL image
image = imgdata * 255
image = Image.fromarray(image.astype('uint8'), 'RGB')
image.show()
这是我的颜色失真输出
如何解决?
问题原因:
您没有使用 np.interp 的 return 值,因此 imgdata 不会被新值替换。因此它保留初始值范围 [0, 255] 并且它的 dtype 也是 np.uint8。当您执行 imgdata * 255 时,它无法满足 np.uint8 中的结果并且它溢出了(但是再次从 0 开始,因为它是无符号的)。
假设:
我假设您想将图像值从 [min(), max()] 映射到 [0, 1],然后通过将其乘以 255.
来重新缩放它。
解决方案:
如果我对您的代码的假设是正确的,请执行以下操作:
imgdata = np.interp(imgdata, (imgdata.min(), imgdata.max()), (0, +1))
else 从代码中删除 (* 255) 并将其更改为,
image = imgdata
您可以通过如下示例数组来测试此溢出:
sample = np.array([10, 20, 30], dtype=np.uint8)
sample2 = sample * 10
print(sample, sample2)
你会看到 sample2 的值是 [100, 200, 44] 而不是 [100, 200, 300]