I wanted to code this RGB to grayscale convertor without any inbuilt Open-CV function. This is how my code looks like
import cv2 , numpy
def GrayConvertor(img):
rows , cols , layers = img.shape
matrix = numpy.zeros((rows , cols))
for i in range(rows):
for j in range(cols):
val = 0.114 * (img[i][j][0]) + 0.587 * (img[i][j][1]) + 0.299 * (img[i][j][2])
fraction = val - int(val)
if fraction >= 0.5:
matrix[i][j] = (int(val) + 1)
else:
matrix[i][j] = int(val)
cv2.imshow("gray" , matrix)
cv2.waitKey(0)
However it shows a blank image , Any ideas?
When you create your
matrixarray withnp.zerosit is, by default, assigneddtype=float. So even though you round and convert your values toint, when writing them intomatrixthey get stored asfloats. If you read the docs forcv.imshowyou will find the following:So everything in your image is getting multiplied by 255, thus messing up your final result.
You can do two things:
matrix, skip all the rounding, and divide your values by 255.matrixwithdtype='uint8'and leave everything unchanged.There is also the fact that you are doing a very poor use of numpy’s capabilities. The two options I gave you above, you can code with no loops or matrix assignments, as