Machine Learning

From RGB to HSV – and return again

The basic idea in the Computer view It recognizes how the pictures are kept and represented. In the disk, image files included in different ways, from loss, pressed JPEG Files that do not lose Ehear files. Once you download a picture in the system and decide on the correct file format, there will be a building like a building like pixels in the picture.

Rgb

Each pixel contains some Color information about that particular point in the picture. Now the common way to represent this color is Rgb Space, where each pixel has three values: red, blue. These amounts explain how much they can each color and will be internalized. So for example, a picture that we have all the prices set in Zero will be dark. If all three prices are set to 100%, the outcome image will be white.

Sometimes the order of these color stations can be changed. Another ordinary order BGRSo the order is returned. This is usually used OpenCV and default when reading or showing pictures.

Alpha Station

Photos can also contain information clearly. In that case, additional Alpha Station is available (RGBA). ALPHA number reflects Pixel for each pixel: Zero Alpha means the Pixel is completely visible and the 100% value represents a complete opaque pixel.

Hsv

Now RGB (a) It is not the only way to represent the colors. In fact, there are many models of different colors that represent color. One of the most helpful models is the Hsv the model. In this model, each color is represented by hue, babery including like property. Hue describes the color tone, regardless of brightness and fullness. Sometimes this is portrayed in a circle of numbers between 0 and 360 or 0 to 0.50, or just between 0 and 100%. Important, it is a cyclical cycle, which means the threats that are threatened around. Second property, the fullness explains intense The color tone, so the filling of 0 results have succeeded gray colors. Finally the price property describes the color brightness, so 0% light is always dark.

Now this color model is very useful in the photo process, because it allows us to finish the color tone from the Saturday and light, which is impossible to do directly Rgb. For example, if you want to be converted between two colors and keep the same at the time of full change, this will be too complicated to achieve the use of Rgb The color model, and in Hsv The model is specifically direct.

Practical examples

We will look at three examples of how to work about these colored epython maths using OpenCV. In the first example, we bring out parts of a particular picture. In the second part, we build a job of using colors between color spaces. Finally, in the third program, we build ongoing pictures between the two colors in continuous light and full light.

1 – color mask

The goal of this part is to find the mask that separates the distinctive colors based on their Hue in the picture. In the next picture, there are fragments of different colors that we want to be separated.

pieces of colored paper

Using OpenCV, we can load the picture and turn it into the HSV color zone. With default images are read in BGR Format, which is why we need the flag cv2.COLOR_BGR2HSV In transition:

Python">import cv2

img_bgr = cv2.imread("images/notes.png")
img_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)

Now in Hsv Photo can apply for color filtering using the cv2.inRange The work is to specify a lower and high supplier with each property (HUE, full, amount). By trying something I had come to the next values ​​in filter:

Equipment Tied down Highly Arrested
Hue 90 11
Babery Out of that 100
Like 150 Fa ten
mask = cv2.inRange(
    src=img_hsv,
    lowerb=np.array([90, 60, 150]),
    upperb=np.array([110, 100, 200]),
)

The Hue filter here is pressed between 90 and 110, equivalent to blue paper at the bottom of the picture. We also put a list of fullness and the amount of light to find an accurate mask.

Showing results, first we need to change one channel mask back to BGR image shape with 3 channels. Additionally, and we can use the mask in the original picture and see the result.

mask_bgr = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
img_bgr_masked = cv2.bitwise_and(img_bgr, img_bgr, mask=mask)

composite = cv2.hconcat([img_bgr, mask_bgr, img_bgr_masked])
cv2.imshow("Composite", composite)

By changing the Hue distance, we can separate some pieces. For example with purple paper, we can clarify the following list:

Property Tied down Highly Arrested
Hue 160 175
Babery 80 11
Like Victory 210

2 – color conversion

While the OpenCV provides effective work to convert full photos into color spaces, they do not offer an outgoing solution to convert one colors into the color spaces. We can write a simple wrapper that forms a small picture of 1 × 1 pixel in the installation color, using the compound function of OpenCV to convert another color location and remove one circles.

def convert_color_space(input: tuple[int, int, int], mode: int) -> tuple[int, int, int]:
    """
    Converts between color spaces

    Args:
        input: A tuple representing the color in any color space (e.g., RGB or HSV).
        mode: The conversion mode (e.g., cv2.COLOR_RGB2HSV or cv2.COLOR_HSV2RGB).

    Returns:
        A tuple representing the color in the target color space.
    """
    px_img_hsv = np.array([[input]], dtype=np.uint8)
    px_img_bgr = cv2.cvtColor(px_img_hsv, mode)
    b, g, r = px_img_bgr[0][0]
    return int(b), int(g), int(r)

Now we can test the job with any color. We can confirm that if we change from RGB -> HSV -> RGB returns to the original format, we find the same price.

red_rgb = (200, 120, 0)

red_hsv = convert_color_space(red_rgb, cv2.COLOR_RGB2HSV)
red_bgr = convert_color_space(red_rgb, cv2.COLOR_RGB2BGR)
red_rgb_back = convert_color_space(red_hsv, cv2.COLOR_HSV2RGB)

print(f"{red_rgb=}") # (200, 120, 0)
print(f"{red_hsv=}") # (18, 255, 200)
print(f"{red_bgr=}") # (0, 120, 200)
print(f"{red_rgb_back=}") # (200, 120, 0)

3 – Continuous Colorial Change

In this third example, we will create a change between two colors in a continuous light and magazine translation. This will be compared to direct translation between the first prices and the last RGBs.

def interpolate_color_rgb(
    start_rgb: tuple[int, int, int], end_rgb: tuple[int, int, int], t: float
) -> tuple[int, int, int]:
    """
    Interpolates between two colors in RGB color space.
    Args:
        start_rgb: The starting color in RGB format.
        end_rgb: The ending color in RGB format.
        t: A float between 0 and 1 representing the interpolation factor.
    Returns:
        The interpolated color in RGB format.
    """
    return (
        int(start_rgb[0] + (end_rgb[0] - start_rgb[0]) * t),
        int(start_rgb[1] + (end_rgb[1] - start_rgb[1]) * t),
        int(start_rgb[2] + (end_rgb[2] - start_rgb[2]) * t),
    )


def interpolate_color_hsv(
    start_rgb: tuple[int, int, int], end_rgb: tuple[int, int, int], t: float
) -> tuple[int, int, int]:
    """
    Interpolates between two colors in HSV color space.
    Args:
        start_rgb: The starting color in RGB format.
        end_rgb: The ending color in RGB format.
        t: A float between 0 and 1 representing the interpolation factor.
    Returns:
        The interpolated color in RGB format.
    """
    start_hsv = convert_color_space(start_rgb, cv2.COLOR_RGB2HSV)
    end_hsv = convert_color_space(end_rgb, cv2.COLOR_RGB2HSV)

    hue = int(start_hsv[0] + (end_hsv[0] - start_hsv[0]) * t)
    saturation = int(start_hsv[1] + (end_hsv[1] - start_hsv[1]) * t)
    value = int(start_hsv[2] + (end_hsv[2] - start_hsv[2]) * t)

    return convert_color_space((hue, saturation, value), cv2.COLOR_HSV2RGB)

We can now write the loop to compare these two methods of translation. To create a picture, using the np.full How to fill all the Array Array pixels in a specified color. Use cv2.hconcat We can combine two horizontal pictures into one picture. Before we can show them, we need to change in OpenCV Fork format.

def run_transition_loop(
    color_start_rgb: tuple[int, int, int],
    color_end_rgb: tuple[int, int, int],
    fps: int,
    time_duration_secs: float,
    image_size: tuple[int, int],
) -> None:
    """
    Runs the color transition loop.

    Args:
        color_start_rgb: The starting color in RGB format.
        color_end_rgb: The ending color in RGB format.
        time_steps: The number of time steps for the transition.
        time_duration_secs: The duration of the transition in seconds.
        image_size: The size of the images to be generated.
    """

    img_shape = (image_size[1], image_size[0], 3)
    num_steps = int(fps * time_duration_secs)

    for t in np.linspace(0, 1, num_steps):
        color_rgb_trans = interpolate_color_rgb(color_start_rgb, color_end_rgb, t)
        color_hue_trans = interpolate_color_hsv(color_start_rgb, color_end_rgb, t)

        img_rgb = np.full(shape=img_shape, fill_value=color_rgb_trans, dtype=np.uint8)
        img_hsv = np.full(shape=img_shape, fill_value=color_hue_trans, dtype=np.uint8)

        composite = cv2.hconcat((img_rgb, img_hsv))
        composite_bgr = cv2.cvtColor(composite, cv2.COLOR_RGB2BGR)

        cv2.imshow("Color Transition", composite_bgr)

        key = cv2.waitKey(1000 // fps) & 0xFF
        if key == ord("q"):
            break

    cv2.destroyAllWindows()

Now we can just call this work in two colors we want to visualize the change. Below I can imagine the change from blue above yellow.

run_transition_loop(
    color_start_rgb=(0, 0, 255),  # Blue
    color_end_rgb=(255, 255, 0),  # Yellow
    fps=25,
    time_duration_secs=5,
    image_size=(512, 256),
)

The difference is very powerful. While the fullness and light remains always in the correct images, they are very changed to distinguishes directly from the Rgb space.


For details of added starting, check the perfect source code in GitTub Repository:


Everything is seen in this post was created by the writer.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button