調整色相飽和度
Photoshop 的色相/飽和度調整,可以對全圖、紅、黃、綠、青、藍、洋紅六個通道進行設置。
每個通道可設置: 色相(hue), 飽和度(satuation), 明度(Lightness)三個調整值。
(一)顏色空間 (Color Space)
顏色空間也稱彩色模型(又稱彩色空間). 常用顏色空間有:RGB, HSL, CYMK, Lab等。
對於RGB圖像,所謂色相/飽和度調整,就是把 RGB 轉為 HSL, 再對色相(H), 飽和度(S), 明度(L)進行調整,然后再轉回RGB.
(二)OpenCV代碼實現
1,我用OpenCV 編寫了多個 顏色空間轉換函數, 在源文件 ColorSpace.hpp, ColorSpace.cpp中
2,我用OpenCV 編寫了一個 HSL類,實現色相/飽和度調整。在源文件 ColorSpace.hpp, ColorSpace.cpp中
3, 使用方法: HSL類有一個屬性channels[7], 定義了7個顏色通道。每個通道有hue, saturation, brightness三個值。設置好所需通道和值,再調用HSL類的adjust()方法即可對圖像進行 色相/飽和度調整。
(三)例程
使用HSL類,進行色相/飽和度調整。
1 #include <iostream>
2 #include "opencv2/core.hpp"
3 #include "opencv2/imgproc.hpp"
4 #include "opencv2/highgui.hpp"
5
6 #include "HSL.hpp"
7
8 using namespace std; 9 using namespace cv; 10
11 static string window_name = "photo"; 12 static Mat src; 13
14 static HSL hsl; 15 static int color = 0; 16 static int hue = 180; 17 static int saturation = 100; 18 static int brightness = 100; 19
20 static void callbackAdjust(int , void *) 21 { 22 Mat dst; 23
24 hsl.channels[color].hue = hue - 180; 25 hsl.channels[color].saturation = saturation - 100; 26 hsl.channels[color].brightness = brightness - 100; 27
28 hsl.adjust(src, dst); 29
30 imshow(window_name, dst); 31 } 32
33 static void callbackAdjustColor(int , void * ) 34 { 35 hue = hsl.channels[color].hue + 180; 36 saturation = hsl.channels[color].saturation + 100; 37 brightness = hsl.channels[color].brightness + 100; 38
39 setTrackbarPos("hue", window_name, hue); 40 setTrackbarPos("saturation", window_name, saturation); 41 setTrackbarPos("brightness", window_name, brightness); 42 callbackAdjust(0, 0); 43 } 44
45
46 int main() 47 { 48 src = imread("building.jpg"); 49
50 if ( !src.data ) { 51 cout << "error read image" << endl; 52 return -1; 53 } 54
55 namedWindow(window_name); 56 createTrackbar("color", window_name, &color, 6, callbackAdjustColor); 57 createTrackbar("hue", window_name, &hue, 2*hue, callbackAdjust); 58 createTrackbar("saturation", window_name, &saturation, 2*saturation, callbackAdjust); 59 createTrackbar("brightness", window_name, &brightness, 2*brightness, callbackAdjust); 60 callbackAdjust(0, 0); 61
62 waitKey(); 63 return 0; 64
65 }
運行效果:
原圖:
對藍色通道(color = 5)調整hue, brightness后
再對全圖(color = 0)調整saturation, brightness后