0
votes

I have a homework assignment I'm desperate to figure out. We've only spent two lecture days on opencv so I'm going in blind with this.

The assignment is to convert an RGB img to grayscale using the luminance formula 0.02126*R+0.7152*G+0.0722*B

So the type of each pixel should be the same as the original image. We're not allowed to use matplot or PIL which is what I've seen a lot of trying to figure this thing out.

The code I have now outputs just a gray image. So instead of graySCALE, it's only gray. I'm so lost, please help.

import cv2
import numpy as np
def togray():
    img = cv2.imread("fruits.jpg")
    cv2.imshow('Original',img)
    height, width, channels = img.shape
    img2 = np.ndarray (shape=(height,width,))
    for i in range(height):
        for j in range(width):
            img2[i,j]=(0*0.2126 + 0.7152*1 + 0.0722*2)

    cv2.imshow('Grayscale',img2)
    cv2.waitKey(0)

togray()
1
In your loop, you're setting all i,j coordinates to the exact same value: (0*0.2126 + 0.7152*1 + 0.0722*2). I haven't used this package, but I imagine you need r, g, and b values in place of 0, 1, and 2.cpander
@Julien now my output is just a smaller gray box.Skrivner

1 Answers

2
votes

Try doing img2 = 0.02126*img[:,:,2] + 0.7152*img[:, :,1] + 0.0722*img[:,:,0]

The comment by Julien was wrong for two reasons: (i) The shape of an image is (m, n, 3) in opencv. This explains why that indexing gives you a smaller box. (ii) opencv channels are BGR, not RGB, so you need to swap the 2 and the 0 indices as I did here. (The actual result should not change too much just considering how small the R and B terms contribute).