Search code examples
javabufferedimagecolorfilter

Image filter with Java BufferedImage: how to change all pixels colors untill they converge to a total gray image


I have a starting BufferedImage ((a) in figure below). I don't know how to call this filter, but I need to transform all figure (a) pixels gradually from (b) to (c), until they are all gray as (d). How can I achieve this? Thanks!

enter image description here


Solution

  • Looks like it could be achieved with linear interpolation. I'll not get into the specifics of the code but just give you an algorithm to put you on the right track.

    Let's assume the colors are represented as RGB float values with a range of [0,1]. So (0.0,0.0,0.0) means 0% red, 0% blue and 0% green; (0.5,0.4,0.3) means 50% red, 40% blue and 30% green. If your colors are in the range [0,255], it should work the same. I prefer the [0,1] range because it works better for certain shaders. You can always divide by 255 to get them into the [0,1] range and multiply by 255 at the end to get them back into the original range.

    You have two images: your base image (let's call it Source) and the fully opaque post-processing effect (in this case pure grey, let's call it Target).

    To linearly interpolate between them, you just add both their RGB values weighted by a factor that changes over time from 0 to 1 for the Source and from 1 to 0 for the Target, so the sum of both RGB values never exceed the color range of their respective channels.

    With your example:

    • For a), you would use RGB(Source) * 1.0 + RGB(Target) * 0.0
    • For b), you would use RGB(Source) * 0.667 + RGB(Target) * 0.333
    • For c), you would use RGB(Source) * 0.333 + RGB(Target) * 0.667
    • For d), you would use RGB(Source) * 0.0 + RGB(Target) * 1.0