一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

变为黑白图像

将彩色图片变成黑白灰度图像的算法,一般是: Gray = Red * 0.299 + Green * 0.587 + Blue * 0.114

Photoshop提供了一个高级的黑白图像调整功能, 可获得更好的黑白图像效果。
Photoshop设置了 red, yellow, green, cyan, blue, magenta 六个 颜色的灰度系数(系数的取值范围是 -1 到 1),
这六个系数的初始值是:
red=0.4, yellow=0.6,  green =0.4, magenta=0.6, blue=0.2, cyan=0.8
如果调大某颜色的系数值,则这种 颜色将更白。反之更黑。
用OpenCV  C++实现上述功能:
1,我编写了一个 BlackWhite类,源码文件两个: BlackWhite.hpp, BlackWhite.cpp
2,BlackWhite类包含六个色调的系数值,设置这些系统值,然后调用 adjust()方法 实施 灰度图像调整。
示范例程:
 1 #include <iostream>
 2 #include "opencv2/core.hpp"
 3 #include "opencv2/imgproc.hpp"
 4 #include "opencv2/highgui.hpp"
 5  
 6 #include "BlackWhite.hpp"
 7  
 8 using namespace std;
 9 using namespace cv;
10  
11  
12 #define BASE 200
13  
14 static string window_name = "photo";
15 static Mat src;
16 static int red     = 40 + BASE;
17 static int yellow  = 60 + BASE;
18 static int green   = 40 + BASE;
19 static int magenta = 60 + BASE;
20 static int blue    = 20 + BASE;
21 static int cyan    = 80 + BASE;
22  
23 static void callbackAdjust(int , void *)
24 {
25     Mat dst;
26     BlackWhite b;
27  
28     //set params
29     b.red = (red - BASE) / 100.0;
30     b.yellow = (yellow - BASE) / 100.0;
31     b.green = (green - BASE) / 100.0;
32     b.magenta = (magenta - BASE) / 100.0;
33     b.blue = (blue - BASE) / 100.0;
34     b.cyan = (cyan - BASE) / 100.0;
35  
36     //adjust Black White
37     b.adjust(src, dst);
38  
39     imshow(window_name, dst);
40 }
41  
42  
43 int main()
44 {
45     src = imread("girl.jpg");
46  
47     if ( !src.data ) {
48         cout << "error read image" << endl;
49         return -1;
50     }
51  
52     namedWindow(window_name);
53  
54     //create trackbars
55     createTrackbar("red", window_name, &red, 500, callbackAdjust);
56     createTrackbar("yellow", window_name, &yellow, 500, callbackAdjust);
57     createTrackbar("green", window_name, &green, 500, callbackAdjust);
58     createTrackbar("cyan", window_name, &cyan, 500, callbackAdjust);
59     createTrackbar("blue", window_name, &blue, 500, callbackAdjust);
60     createTrackbar("magenta", window_name, &magenta, 500, callbackAdjust);
61  
62     callbackAdjust(0, 0);
63  
64     waitKey();
65     return 0;
66 }
运行效果:
原图:
使用默认参数值时的黑白图片效果:

调整参数值后的黑白图片效果(暗化绿背景、突出人脸(红)):

posted on 2020-10-12 10:39  一杯清酒邀明月  阅读(987)  评论(1编辑  收藏  举报