将所有非黑色像素转换为一种颜色不会产生预期的输出 [英] Converting all non-black pixels into one colour doesn't produce expected output

查看:214
本文介绍了将所有非黑色像素转换为一种颜色不会产生预期的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试选择非黑色像素,然后将其着色为黑色,黑色像素为白色.我使用了提供的解决方案堆栈溢出,但到目前为止它对我不起作用.

I am trying to select non-black pixel and then colour them to black and the black pixels to white. I used a solution provided on Stack Overflow but so far it isn't working for me.

import numpy as np
import matplotlib.pyplot as plt


image = plt.imread('Perforated_carbon/faltu.png')
plt.imshow(image)
plt.show()

image_copy = image.copy()

black_pixels_mask = np.all(image == [0, 0, 0], axis=-1)

non_black_pixels_mask = ~black_pixels_mask
# or non_black_pixels_mask = np.any(image != [0, 0, 0], axis=-1)  

image_copy[black_pixels_mask] = [255, 255, 255]
image_copy[non_black_pixels_mask] = [0, 0, 0]

plt.imshow(image_copy)
plt.show()

这是我当前正在获取的图片

我理想的情况是这样

其他信息:

>>> image.shape
(256, 192, 3)
>>> image.dtype
dtype('float32')
>>> import matplotlib; print(matplotlib.__version__)
2.0.0

推荐答案

问题是,在matplotlib版本< 2.2.0中,没有 Bizzare matplotlib显示为浮点的图像时的行为

The problem is that in matplotlib versions <2.2.0 there was no normalization and any warnings when you passed an array to imshow that contained data out of expected range. So, you could get some unexpected results, like here: Bizzare matplotlib behaviour in displaying images cast as floats

如果将您的matplotlib更新到版本> = 2.2.0,则在运行问题中的代码时,您将看到以下警告:

If you update your matplotlib to version >=2.2.0, when running the code in the question, you will see the following warning:

Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).

,生成的图像将是您想要的图像.所以,我的建议是更换

and the produced image will be the one that you would want to get. So, my advice for you is to replace

image_copy[black_pixels_mask] = [255, 255, 255]

作者

image_copy[black_pixels_mask] = [1, 1, 1]

,还希望更新matplotlib.

and it would be also desirable to update matplotlib.

这是GitHub上的相关问题: imshow不能规范RGB中的颜色范围图片和拉取请求:将RGB数据剪切到imshow的有效范围内.

Here is related issue on GitHub: imshow doesn't normalize the color range in RGB images, and a pull request: Clip RGB data to valid range for imshow.

这篇关于将所有非黑色像素转换为一种颜色不会产生预期的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆