Home > Software design >  RGB to V (from HSV)
RGB to V (from HSV)

Time:04-24

I am trying to convert an RGB image to its Value component. I cannot use the RGB2HSV function because I have been instructed to convert it without it. If I am not mistaken, the value of an image is the maximum of the R,G and B components in the pixel; so this is what I have tried to implement.

'''

    rgb_copy = self.rgb.copy()

    width, height, other = rgb_copy.shape
    for i in range(0, width-1):
        for j in range(0, height-1):
            # normalize the rgb values
            [r, g, b] = self.rgb[i, j]
            r_norm = r/255.0
            g_norm = g/255.0
            b_norm = b/255.0

            # find the maximum of the three values
            max_value = max(r_norm, g_norm, b_norm)

            rgb_copy[i, j] = (max_value, max_value, max_value)

    cv2.imshow('Value', rgb_copy)
    cv2.waitKey()

'''

This unfortunately does not seem to work. It returns just a black image which is not the same as the Value component when I convert it using the inbuilt function.

Can anyone help or see where I have gone wrong?

CodePudding user response:

To elaborate on my comment above:

Because you attempt to normalize the RGB values by dividing by 255, I assume your RGB image is a 3 channel, unsigned char image (each channel is an unsigned char value between 0..255).

When yo clone it with:

rgb_copy = self.rgb.copy()

You make rgb_copy an image of the same type (i.e. 3 channel unsigned char). Then you attempt to populate it with normalized 0..1 float values per channel. Instead you can simply put the max of the RGB channels per pixel.

Something like:

rgb_copy = self.rgb.copy()
width, height, other = rgb_copy.shape
for i in range(0, width - 1):
    for j in range(0, height - 1):
        # find the maximum of the three values
        max_value = max(self.rgb[i, j])
        rgb_copy[i, j] = (max_value, max_value, max_value)

cv2.imshow('Value', rgb_copy)
cv2.waitKey()
  • Related