0
votes

is there a way to change an image to grayscale without using cmap in matpotlib? my function is

def grayscale(image):
    img = image.copy()
    r=img[:,:,0]*0.3
    g=img[:,:,1]*0.59
    b=img[:,:,2]*0.11
    gray=r+g+b
    img=np.dstack((gray,gray,gray))
    return img
plt.imshow(img)

However, the image I got is just black and white, not in grayscale TT. Then when I tried using gray=r+g+b,plt.imshow(img), I got a green and yellow picture. I have tried searching everywhere to get clues and all I found was the use of cmaps. However the project I am doing doesn't allow us to use cmap.

1

1 Answers

1
votes

Here is a working solution using your code - you should add your picture path in the image_path variable:

import numpy as np
from PIL import Image
import cv2
def grayscale(image):
    img = np.asarray(Image.open(image))
    r = img[:,:,0]*0.3
    g = img[:,:,1]*0.59
    b = img[:,:,2]*0.11
    gray = r+g+b
    return gray
image_path = "test.jpg"
img = grayscale(image_path)
cv2.imwrite('greyscale.jpg',img)

The trick was that you did not load the image in a proper way.