简体   繁体   中英

Convert RGB image to black and white

I have the following RGB image (shape of (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).

I made (with help from the internet) the following 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:

(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:

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). 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.

And yeah, specify the colormap for matplotlib :

plt.imshow(im[:,:,1], cmap='gray')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM