I have a small question hope you guys can help me. I know that to convert a RGB image to grayscale without using numpy, we can use:
img = cv2.imread(input_file, cv2.IMREAD_COLOR)
r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
img_gray = 0.2989 * r 0.5870 * g 0.1140 * b
Now I want to read the image by BGR scale then convert that BGR image to grayscale not using cv2.COLOR_BGR2GRAY
, how can I do it with the similar code above?
CodePudding user response:
OpenCV will read the file into memory in BGR order, even though it is RGB on disk. That's just the way it works. So you need to change your second line to:
b, g, r = img[:, :, 0], img[:, :, 1], img[:, :, 2]
Then your third line will work correctly, although you may want to make unsigned 8-bit integers with:
img_gray = (0.2989 * r 0.5870 * g 0.1140 * b).astype(np.uint8)
By the way, you could actually do it faster with numpy
like this:
import numpy as np
grey = np.dot(img[...,::-1], [0.299, 0.587, 0.114]).astype(np.uint8)