Open CV - Python RGB to GRAY Converter
I wanted to encode this RGB to black and white converter without built-in 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?
source to share
When you create an array matrix
with np.zeros
, the default is assigned to it dtype=float
. So even if you round up and convert your values ββto int
, when you write them to, matrix
they are stored as float
s. If you've read the docs forcv.imshow
, you'll find the following:
- If the image is a 32-bit floating point, the pixel values ββare multiplied by 255. That is, the value range [0,1] is mapped to [0255].
This way, everything in your image is multiplied by 255, which results in the final result.
You can do two things:
- Floating point
matrix
, skip all rounding and divide the values ββby 255. - Explicitly create
matrix
withdtype='uint8'
and leave everything unchanged.
There is also the fact that you are not making good use of numpy's capabilities. The two options I gave you above, you can code without loops or matrix assignments, since
rgb2k = np.array([0.114, 0.587, 0.299])
matrix_int = np.round(np.sum(img * rgb2k, axis=-1)).astype('uint8')
matrix_float = np.sum(img * rgb2k, axis=-1) / 255
source to share
try:
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])
matrix[i][j] = round(val)
cv2.imshow("gray" , matrix)
cv2.waitKey(0)
source to share