您好,您可以参考下面的 C++ 代码,这里我仅更改色调值,如果您想更改饱和度和值,只需创建一个带有滑块位置值的 Mat,并使用适当的通道(sat 或 val)进行添加或减去。
int H=50;
Mat src, hsv, dst;
char window_name[30] = "HSV Demo";
void HSV_Demo( int, void* );
int main( int argc, char** argv ){
src = imread( "car.jpg", 1 );
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
createTrackbar( "Hue", window_name,&H, 179, HSV_Demo );
HSV_Demo( 0, 0 );
while(true)
{
int c;
c = waitKey( 20 );
if( (char)c == 27 )
break;
if( (char)c == 's' ) imwrite("result.jpg",dst);
}
}
void HSV_Demo( int, void* )
{
cvtColor(src, hsv,CV_BGR2HSV);
Mat channel[3];
split(hsv,channel);
channel[0].setTo(H);
Mat tmp[3] = { channel[0],channel[1],channel[2] };
merge(tmp,3,dst);
cvtColor(dst, dst,CV_HSV2BGR);
imshow( window_name, dst );
}
Edit:-
根据下面的评论,这里是使用 HSV 通过保留阴影创建黑白图像的步骤。
请注意,下面的方法并不完美,因为您可以看到边缘不规则,但您可以尝试下面的方法或改进下面的方法本身。
这个想法很简单,我们将只考虑值通道并添加一些常量(滑块位置)以创建白色并减去以创建黑色,然后使用将其转换为 BGR 图像cvtColor()。如果加法或减法结果超出范围,阴影可能会消失。
在相加或相减之前,我们将通过分割色调(此处为红色)来创建一个掩模图像,并使用常量(滑块位置)和掩模创建一个新的 Mat,以便在相加或相减时背景保持不变。
void HSV_Demo( int, void* )
{
cvtColor(src, hsv,CV_BGR2HSV);
Mat channel[3];
split(hsv,channel);
Mat thr1,thr2;
inRange(hsv,Scalar(165,50,50),Scalar(179,255,255), thr1); //Create mask to change to avoid background
inRange(hsv,Scalar(0,50,50),Scalar(10,255,255), thr2); //Create mask to change to avoid background
thr1=thr1+thr2;
if(H>255){
if(H) H-=255;
thr1.setTo(H,thr1); //Set the image to add to value which will create white color
// channel[1].setTo(0);
channel[2]=channel[2]+thr1;
}
else {
H=255-H;
thr1.setTo(H,thr1);
// channel[1].setTo(0);
channel[2]=channel[2]-thr1;//Set the image to subtract from value which will create black color
}
//Convert single channel to BGR
Mat BGR;
cvtColor(channel[2], BGR,CV_GRAY2BGR);
imshow( window_name, BGR );
/* Mat tmp[3] = { channel[0],channel[1],channel[2] };
merge(tmp,3,dst);
cvtColor(dst, dst,CV_HSV2BGR);
imshow( window_name, dst );*/
}
在上面的代码中,通过取消注释代码,您将得到相同的结果。
Result:-