I sum each pixel's Red, Green and Blue values and divide the sum by 3:
gray_image = (image[:,:,0] + image[:,:,1] + image[:,:,2]) / 3
This is what I got:

My code is:
import matplotlib.image as pltim
import matplotlib.pyplot as plt
import numpy as np
def rgb2gray(image):
imageHeight = len(image)
imageWidth = len(image[0])
grayImage = np.empty([imageHeight, imageWidth], dtype=np.uint8)
for i in range(imageHeight):
for j in range(imageWidth):
grayImage[i][j] = int((image[i][j][0] + image[i][j][1] + image[i][j][2]) / 3)
return grayImage
class RetargetedImage:
imageDirectory = ""
image = None
grayImage = None
def __init__(self, imageDirectory):
self.imageDirectory = imageDirectory
self.image = pltim.imread(self.imageDirectory)
self.grayImage = rgb2gray(self.image)
def showOriginalImage(self):
plt.imshow(self.image)
plt.show()
def showGrayImage(self):
plt.imshow(self.grayImage)
plt.show()
example1 = RetargetedImage("treeMedium.jpg")
example1.showGrayImage()
And this is the original image:

Where am I doing wrong?
plt.imshow(..., cmap='gray')forloops (they are very slow and error-prone), usenp.dot()instead.... stackoverflow.com/a/58531115/2836621