Search code examples
pythonopencvimage-processingcolor-spacecontrast

Get contrast for each channel in an image opencv python


How to calculate each channel contrast in images? Since they are lot of contrast definitions out there

  1. Webar Contrast
  2. Michelson Contrast
  3. RMS contrast

I need to calculate these contrasts.


Solution

  • from PIL import Image
    import numpy as np
    from numpy import mean, sqrt, square
    im = Image.open("leaf.jpg") # Image file name
    pixels = list(im.getdata())
    width, height = im.size
    pixels = np.asarray([pixels[i * width:(i + 1) * width] for i in range(height)], dtype=int)
    
    ch_1 = pixels[:,:,0]
    ch_2 = pixels[:,:,1]
    ch_3 = pixels[:,:,2]
    
    rms_of_ch1 = sqrt(mean(square(ch_1)))
    rms_of_ch2 = sqrt(mean(square(ch_2)))
    rms_of_ch3 = sqrt(mean(square(ch_3)))