Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the color of an image based on RGB value

Situation:

You have an image with 1 main color and you need to convert it to another based on a given rgb value.

Problem:

There are a number of different, but similar shades of that color that also need to be converted, which makes a simple 'change-all-(0,0,0)-pixels-to-(0,100,200)' solution worthless.

If anyone can point me in the right direction as far as an algorithm or an image manipulation technique that would make this task more manageable that'd be great.

I've been using PIL to attempt this problem but any general tips would be nice.

edit:

Also, I've used this other SO answer (Changing image hue with Python PIL) to do part of what I'm asking (the hue change), but It doesn't take into consideration the saturation or value

edit: http://dpaste.org/psk5C/ shows using pil to look at the rgb values that I have to work with and the hsv's that go along with some.

like image 320
tippenein Avatar asked Aug 06 '12 16:08

tippenein


1 Answers

Refering to the solution in the linked question: You can adjust the shift_hue() function to adjust hue, saturation and value instead of just hue. That should then allow you to shift all of these parameters just as you like.

Original:

def shift_hue(arr, hout):
    r, g, b, a = np.rollaxis(arr, axis=-1)
    h, s, v = rgb_to_hsv(r, g, b)
    h = hout
    r, g, b = hsv_to_rgb(h, s, v)
    arr = np.dstack((r, g, b, a))
    return arr

Adjusted Version:

def shift_hsv(arr, delta_h, delta_, delta_v):
    r, g, b, a = np.rollaxis(arr, axis=-1)
    h, s, v = rgb_to_hsv(r, g, b)
    h += delta_h
    s += delta_s
    v += delta_v
    r, g, b = hsv_to_rgb(h, s, v)
    arr = np.dstack((r, g, b, a))
    return arr

Assuming you know the base color of your original image and the target color you want, you can easily compute the deltas:

base_h, base_s, base_v = rgb_to_hsv(base_r, base_g, base_b)
target_h, target_s, target_v = rgb_to_hsv(target_r, target_g, target_b)
delta_h, delta_s, delta_v  = target_h - base_h, target_s - base_s, target_v - base_v
like image 101
Michael Mauderer Avatar answered Sep 20 '22 21:09

Michael Mauderer