[英]Convert RGB image to black and white
I have the following RGB image (shape of (3, 50, 200)):我有以下 RGB 图像(形状为 (3, 50, 200)):
I want to reduce dimensions by converting the image to pure black and white (this image looks black and white, but actually it has 3 channels as I mentioned).我想通过将图像转换为纯黑白来减小尺寸(此图像看起来是黑白的,但实际上它有 3 个通道,正如我所提到的)。
I made (with help from the internet) the following function:我(在互联网的帮助下)制作了以下 function:
def rgb2gray(rgb):
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = (0.2989 * r + 0.5870 * g + 0.1140 * b)
for x in range(rgb.shape[1]):
for y in range(rgb.shape[0]):
if gray[y][x]>128: #if bright
gray[y][x] = 255.0 #white
else:
gray[y][x] = 0.0 #black
return gray
Then I ran:然后我跑了:
im = cv2.imread("samples/55y2m.png")
print(im.shape)
print(rgb2gray(im).shape)
plt.imshow(rgb2gray(im))
And got the following output:并得到以下output:
(50, 200, 3) #for the input
(50, 200) #for the output
Why the image is yellow and purple, and how can I change it to black and white?为什么图像是黄色和紫色,如何将其更改为黑白?
ps I tried to change the function to: ps 我尝试将 function 更改为:
def rgb2gray(rgb):
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = (0.2989 * r + 0.5870 * g + 0.1140 * b)
for x in range(rgb.shape[1]):
for y in range(rgb.shape[0]):
if gray[y][x]>128:
rgb[y][x] = 255.0 #changed
else:
rgb[y][x] = 0.0 #changed
return rgb #changed
And I actually got pure black and white image, but it was 3 channels (RGB).我实际上得到了纯黑白图像,但它是 3 通道 (RGB)。 So I tried to remove the last axis, and got purple and yellow again.所以我试着去掉最后一个轴,又变成了紫色和黄色。
You don't need this:你不需要这个:
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = (0.2989 * r + 0.5870 * g + 0.1140 * b)
because your image is already grayscale, which means R == G == B
, so you may take GREEN channel (or any other if you like) and use it.因为您的图像已经是灰度的,这意味着R == G == B
,所以您可以使用绿色通道(或任何其他,如果您愿意)并使用它。
And yeah, specify the colormap for matplotlib
:是的,指定matplotlib
的颜色图:
plt.imshow(im[:,:,1], cmap='gray')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.