Search code examples
pythonnumpyopencvimage-processingcolor-space

How to set the value of the V-channel of the HSV color space to a constant value


I'm working on an Object detection problem where i have to detect small colored cars. I used color as main feature representation of the target object and applied histogram back_projection.

However, as you know it is hard to maintain color consistency because colors are highly illuminance-variant. However, if i could measure how lightness changes, i could control the chnage of the color.

Therefore, i converted video frame into HSV since the V-channel represents the lightness (brightness) of the image, i calculated the min/max mean of that channel using the following code:

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

cap=cv.VideoCapture(r'C:/Users/kjbaili/Docum_changes.mp4')

Mean_list=[]
while cap.isOpened:
    ret,frame=cap.read()
    if ret!=True:
        print("cant open Video, please check your source")
        break
    else:
    




     HSV=cv.cvtColor(frame.copy(),cv.COLOR_BGR2HSV)

     h,s,v=cv.split(HSV)
 
 
 
     cv.imshow('HSV_image',HSV)
     MEAN_V=v.mean()
     Mean_list.append(MEAN_V)   
 

     print('mean_V',MEAN_V)
     cv.waitKey(1)
print('Minimum_ lightness  ', min(Mean_list))
print('Maximum_lightness   ',max( Mean_list))
cv.destroyAllWindows()

and results are

Minimum_ lightness   137.57618546786645
Maximum_lightness    172.9926900112821

So by observing the video, the value of the V-channel drops from 172-->137.Therefore, if i set the value of the v channel to be always 172, the colors in the video will theoretically be the same.

So my question is: How can i, if possible, set the value of V-channel to a constant value= 172?

Thanks in advance


Solution

  • You can set the value of a channel to some constant in Python/OpenCV as follows using numpy syntax

    v[:,:] = 172
    

    That sets every x,y grayscale value in the image to 172.