Reputation: 79
I'm trying to convert a color image to grayscale, but I would like to use the max value of the channels as the grayscale value. Given the sample image:
[[[0,100,200] [25,55,105] [11,22,33]],
[[0,1,1] [222,111,0] [255,2,20]],
[[0,17,0] [0,0,0] [88,99,77]]]
I would like the resulting grayscale image to be
[[[200] [105] [33]],
[[1] [222] [255]],
[[17] [0] [99]]]
Is there a better/faster method than splitting the channels and iterating through the image?
def get_max_grayscale_image(img_mtx):
img_b, img_g, img_r = cv2.split(img_mtx.copy())
height, width = img_b.shape[0:2]
gray_max_image = np.zeros((height, width), np.uint8)
for i in range(height):
for j in range(width):
gray_max_image [i, j] = max(img_b[i, j], img_g[i, j], img_r [i, j])
return gray_max_image
Upvotes: 1
Views: 61
Reputation: 92461
You can use ndarray.max()
and pass it the axis you want. Setting keepdims
to True
will keep this as a two dimensional list. If you want it flattened, you can leave that off or set it to False
:
import numpy as np
im = np.array([
[0,100,200],
[25,55,105],
[11,22,33],
[0,1,1],
[222,111,0],
[255,2,20],
[0,17,0],
[0,0,0],
[88,99,77]
])
im.max(axis=1, keepdims=True)
This will produce a new array:
array([[200],
[105],
[ 33],
[ 1],
[222],
[255],
[ 17],
[ 0],
[ 99]])
Upvotes: 2