Search code examples
pythonrubyimage-processingvips

Subtract 2 identical images (B&W and colorful) to get color difference


I have mostly black and white image, with some parts in color (let's say it's yellow and green). I would like to find out those colors.

For that, I suppose I might convert image to black & white, and then compare b & w image with original one to find the difference. But I'm not quite sure which algorithm I should use to do that.

Something like that in pseudocode:

image = image_from_file('image.jpg')
bw_image = image.convert_to_bw
diff_image = (bw_image - image)
# Build histogram w/o black and white parts, only color ones
diff_image.histogram

I'm primary focused on libvips to do that, but I just need an advice of how to do that in general, then I'll be able to code that.

I would also appreciate if you know any other way to do what I described above.


Solution

  • In ruby-vips you could do:

    require 'vips'
    
    a = Vips::Image.new_from_file ARGV[0]
    
    # convert to LCh colourspace
    a = a.colourspace "lch"
    
    # Chroma (band 1) > 0 means we have some colour ... take > 10, since things 
    # like jpg compression will add some colour noise we are not 
    # interested in
    mask = a[1] > 10
    
    # the mask image will have 255 for TRUE pixels and 0 for FALSE
    mask.write_to_file "mask.png"
    

    The mask image might not be very helpful, but I'm not clear exactly what output you need.

    LCh colourspace is useful here: band 1 (ie. C) is the distance of the pixel from the neutral axis, exactly what you want, I think.