Changing the color of an image based on RGB value

若如初见. 提交于 2019-12-22 05:06:12

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11832055/changing-the-color-of-an-image-based-on-rgb-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!