How to change saturation values with opencv?

2020-07-03 08:56发布

问题:

In order to add constant value to each pixel's saturation value, I do this in double loops. I wonder if there is any simpler and faster command achieving this.

回答1:

Mat img(200, 300, CV_8UC1);

Mat saturated;

double saturation = 10;
double scale = 1;

// what it does here is dst = (uchar) ((double)src*scale+saturation); 
img.convertTo(saturated, CV_8UC1, scale, saturation); 

EDIT

If by saturation, you mean the S channel in a HSV image, you need to separe your image in three channels with split(), apply the saturation correction to the S channel, and then put them together with merge().



回答2:

For the experiments I attempted, the alternative method of splitting hsv values, adjusting the individual channels and then doing a merge gave a better performance. Below is what worked for me many times faster as compared to looping through pixels:

(h, s, v) = cv2.split(imghsv)
s = s*satadj
s = np.clip(s,0,255)
imghsv = cv2.merge([h,s,v])

Note that I had converted the values to float32 during BGR2HSV transformation to avoid negative values during saturation transformation to due uint8 (default) overflow:

imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype("float32")

And converted it back to default uint8 after my saturation adjustment:

imgrgb = cv2.cvtColor(imghsv.astype("uint8"), cv2.COLOR_HSV2BGR)


标签: opencv