File: colorize.cpp

package info (click to toggle)
opencv 4.5.1%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 268,248 kB
  • sloc: cpp: 969,170; xml: 682,525; python: 36,732; lisp: 30,170; java: 25,155; ansic: 7,927; javascript: 5,643; objc: 2,041; sh: 935; cs: 601; perl: 494; makefile: 145
file content (417 lines) | stat: -rw-r--r-- 13,433 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417

#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/core/utility.hpp"

#include <time.h>
#include <vector>
#include <iostream>
#include <opencv2/ximgproc.hpp>



using namespace cv;

#ifdef HAVE_EIGEN

#define MARK_RADIUS 5
#define PALLET_RADIUS 100
int max_width = 1280;
int max_height = 720;

static int globalMouseX;
static int globalMouseY;
static int selected_r;
static int selected_g;
static int selected_b;
static bool globalMouseClick = false;
static bool glb_mouse_left = false;
static bool drawByReference = false;
static bool mouseDraw = false;
static bool mouseClick;
static bool mouseLeft;
static int mouseX;
static int mouseY;

cv::Mat mat_draw;
cv::Mat mat_input_gray;
cv::Mat mat_input_reference;
cv::Mat mat_input_confidence;
cv::Mat mat_pallet(PALLET_RADIUS*2,PALLET_RADIUS*2,CV_8UC3);


static void mouseCallback(int event, int x, int y, int flags, void* param);
void drawTrajectoryByReference(cv::Mat& img);
double module(Point pt);
double distance(Point pt1, Point pt2);
double cross(Point pt1, Point pt2);
double angle(Point pt1, Point pt2);
int inCircle(Point p, Point c, int r);
void createPlate(Mat &im1, int radius);


#endif

const String keys =
    "{help h usage ?     |                | print this message                                                }"
    "{@image             |                | input image                                                       }"
    "{sigma_spatial      |8               | parameter of post-filtering                                       }"
    "{sigma_luma         |8               | parameter of post-filtering                                       }"
    "{sigma_chroma       |8               | parameter of post-filtering                                       }"
    "{dst_path           |None            | optional path to save the resulting colorized image               }"
    "{dst_raw_path       |None            | optional path to save drawed image before filtering               }"
    "{draw_by_reference  |false           | optional flag to use color image as reference                     }"
    ;



int main(int argc, char* argv[])
{

    CommandLineParser parser(argc,argv,keys);
    parser.about("fastBilateralSolverFilter Demo");
    if (parser.has("help"))
    {
        parser.printMessage();
        return 0;
    }

#ifdef HAVE_EIGEN

    String img = parser.get<String>(0);
    double sigma_spatial  = parser.get<double>("sigma_spatial");
    double sigma_luma  = parser.get<double>("sigma_luma");
    double sigma_chroma  = parser.get<double>("sigma_chroma");
    String dst_path = parser.get<String>("dst_path");
    String dst_raw_path = parser.get<String>("dst_raw_path");
    drawByReference = parser.get<bool>("draw_by_reference");

    mat_input_reference = cv::imread(img, IMREAD_COLOR);
    if (mat_input_reference.empty())
    {
        std::cerr << "input image '" << img << "' could not be read !" << std::endl << std::endl;
        parser.printMessage();
        return 1;
    }

    cvtColor(mat_input_reference, mat_input_gray, COLOR_BGR2GRAY);

    if(mat_input_gray.cols > max_width)
    {
        double scale = float(max_width) / float(mat_input_gray.cols);
        cv::resize(mat_input_reference, mat_input_reference, cv::Size(), scale, scale);
        cv::resize(mat_input_gray, mat_input_gray, cv::Size(), scale, scale);
    }

    if(mat_input_gray.rows > max_height)
    {
        double scale = float(max_height) / float(mat_input_gray.rows);
        cv::resize(mat_input_reference, mat_input_reference, cv::Size(), scale, scale);
        cv::resize(mat_input_gray, mat_input_gray, cv::Size(), scale, scale);
    }


    float filtering_time;
    std::cout << "mat_input_reference:" << mat_input_reference.cols<<"x"<< mat_input_reference.rows<< std::endl;
    std::cout << "please select a color from the palette, by clicking into that," << std::endl;
    std::cout << "  then select a coarse region in the image to be coloured." << std::endl;
    std::cout << "  press 'escape' to see the final coloured image." << std::endl;


    cv::Mat mat_gray;
    cv::cvtColor(mat_input_reference, mat_gray, cv::COLOR_BGR2GRAY);

    cv::Mat target = mat_input_reference.clone();
    cvtColor(mat_gray, mat_input_reference, COLOR_GRAY2BGR);

    cv::namedWindow("draw", cv::WINDOW_AUTOSIZE);

    // construct pallet
    createPlate(mat_pallet, PALLET_RADIUS);
    selected_b = 0;
    selected_g = 0;
    selected_r = 0;

    cv::Mat mat_show(target.rows,target.cols+PALLET_RADIUS*2,CV_8UC3);
    cv::Mat color_select(target.rows-mat_pallet.rows,PALLET_RADIUS*2,CV_8UC3,cv::Scalar(selected_b, selected_g, selected_r));
    target.copyTo(Mat(mat_show,Rect(0,0,target.cols,target.rows)));
    mat_pallet.copyTo(Mat(mat_show,Rect(target.cols,0,mat_pallet.cols,mat_pallet.rows)));
    color_select.copyTo(Mat(mat_show,Rect(target.cols,PALLET_RADIUS*2,color_select.cols,color_select.rows)));

    cv::imshow("draw", mat_show);
    cv::setMouseCallback("draw", mouseCallback, (void *)&mat_show);
    mat_input_confidence = 0*cv::Mat::ones(mat_gray.size(),mat_gray.type());

    int show_count = 0;
    while (1)
    {
            mouseX = globalMouseX;
            mouseY = globalMouseY;
            mouseClick = globalMouseClick;
            mouseLeft = glb_mouse_left;


        if (mouseClick)
        {
            drawTrajectoryByReference(target);

            if(show_count%5==0)
            {
                cv::Mat target_temp(target.size(),target.type());
                filtering_time = static_cast<float>(getTickCount());
                if(mouseDraw)
                {
                    cv::cvtColor(target, target_temp, cv::COLOR_BGR2YCrCb);
                    std::vector<cv::Mat> src_channels;
                    std::vector<cv::Mat> dst_channels;

                    cv::split(target_temp,src_channels);

                    cv::Mat result1 = cv::Mat(mat_input_gray.size(),mat_input_gray.type());
                    cv::Mat result2 = cv::Mat(mat_input_gray.size(),mat_input_gray.type());

                    dst_channels.push_back(mat_input_gray);
                    cv::ximgproc::fastBilateralSolverFilter(mat_input_gray,src_channels[1],mat_input_confidence,result1,sigma_spatial,sigma_luma,sigma_chroma);
                    dst_channels.push_back(result1);
                    cv::ximgproc::fastBilateralSolverFilter(mat_input_gray,src_channels[2],mat_input_confidence,result2,sigma_spatial,sigma_luma,sigma_chroma);
                    dst_channels.push_back(result2);

                    cv::merge(dst_channels,target_temp);
                    cv::cvtColor(target_temp, target_temp, cv::COLOR_YCrCb2BGR);
                }
                else
                {
                  target_temp = target.clone();
                }
                filtering_time = static_cast<float>(((double)getTickCount() - filtering_time)/getTickFrequency());
                std::cout << "solver time: " << filtering_time << "s" << std::endl;

                cv::Mat color_selected(target_temp.rows-mat_pallet.rows,PALLET_RADIUS*2,CV_8UC3,cv::Scalar(selected_b, selected_g, selected_r));
                target_temp.copyTo(Mat(mat_show,Rect(0,0,target_temp.cols,target_temp.rows)));
                mat_pallet.copyTo(Mat(mat_show,Rect(target_temp.cols,0,mat_pallet.cols,mat_pallet.rows)));
                color_selected.copyTo(Mat(mat_show,Rect(target_temp.cols,PALLET_RADIUS*2,color_selected.cols,color_selected.rows)));
                cv::imshow("draw", mat_show);
            }
            show_count++;
        }
        if (cv::waitKey(2) == 27)
            break;
    }
    mat_draw = target.clone();
    cv::cvtColor(target, target, cv::COLOR_BGR2YCrCb);

    std::vector<cv::Mat> src_channels;
    std::vector<cv::Mat> dst_channels;

    cv::split(target,src_channels);

    cv::Mat result1 = cv::Mat(mat_input_gray.size(),mat_input_gray.type());
    cv::Mat result2 = cv::Mat(mat_input_gray.size(),mat_input_gray.type());

    filtering_time = static_cast<float>(getTickCount());

    // dst_channels.push_back(src_channels[0]);
    dst_channels.push_back(mat_input_gray);
    cv::ximgproc::fastBilateralSolverFilter(mat_input_gray,src_channels[1],mat_input_confidence,result1,sigma_spatial,sigma_luma,sigma_chroma);
    dst_channels.push_back(result1);
    cv::ximgproc::fastBilateralSolverFilter(mat_input_gray,src_channels[2],mat_input_confidence,result2,sigma_spatial,sigma_luma,sigma_chroma);
    dst_channels.push_back(result2);

    cv::merge(dst_channels,target);
    cv::cvtColor(target, target, cv::COLOR_YCrCb2BGR);

    filtering_time = static_cast<float>(((double)getTickCount() - filtering_time)/getTickFrequency());
    std::cout << "solver time: " << filtering_time << "s" << std::endl;



    cv::imshow("mat_draw",mat_draw);
    cv::imshow("output",target);

    if(dst_path!="None")
    {
        imwrite(dst_path,target);
    }
    if(dst_raw_path!="None")
    {
        imwrite(dst_raw_path,mat_draw);
    }

    cv::waitKey(0);



#else
    std::cout << "Can not find eigen, please build with eigen by set WITH_EIGEN=ON" << '\n';
#endif

    return 0;
}


#ifdef HAVE_EIGEN
static void mouseCallback(int event, int x, int y, int, void*)
{
    switch (event)
    {
        case cv::EVENT_MOUSEMOVE:
            if (globalMouseClick)
            {
                globalMouseX = x;
                globalMouseY = y;
            }
            break;

        case cv::EVENT_LBUTTONDOWN:
            globalMouseClick = true;
            globalMouseX = x;
            globalMouseY = y;
            break;

        case cv::EVENT_LBUTTONUP:
            glb_mouse_left = true;
            globalMouseClick = false;
            break;
    }
}

void drawTrajectoryByReference(cv::Mat& img)
{
    int i, j;
    uchar red, green, blue;
    float gray;
    int y, x;
    int r = MARK_RADIUS;
    int r2 = r * r;
    uchar* colorPix;
    uchar* grayPix;

    if(mouseY < PALLET_RADIUS*2 && img.cols <= mouseX && mouseX < img.cols+PALLET_RADIUS*2)
    {
        colorPix = mat_pallet.ptr<uchar>(mouseY, mouseX - img.cols);
        // colorPix = mat_pallet.ptr<uchar>(mouseY, mouseX);
        selected_b = *colorPix;
        colorPix++;
        selected_g = *colorPix;
        colorPix++;
        selected_r = *colorPix;
        colorPix++;
        std::cout << "x y:("<<mouseX<<"," <<mouseY<< " rgb_select:("<< selected_r<<","<<selected_g<<","<<selected_b<<")" << '\n';
    }
    else
    {
        mouseDraw = true;
        y = mouseY - r;
        for(i=-r; i<r+1 ; i++, y++)
        {
            x = mouseX - r;
            colorPix = mat_input_reference.ptr<uchar>(y, x);
            grayPix = mat_input_gray.ptr<uchar>(y, x);
            for(j=-r; j<r+1; j++, x++)
            {
                if(i*i + j*j > r2)
                {
                    colorPix += mat_input_reference.channels();
                    grayPix += mat_input_gray.channels();
                    continue;
                }

                if(y<0 || y>=mat_input_reference.rows || x<0 || x>=mat_input_reference.cols)
                {
                    break;
                }

                blue = *colorPix;
                colorPix++;
                green = *colorPix;
                colorPix++;
                red = *colorPix;
                colorPix++;
                gray = *grayPix;
                grayPix++;
                mat_input_confidence.at<uchar>(y,x) = 255;
                float draw_y = 0.229f*(float(selected_r)) + 0.587f*(float(selected_g)) + 0.114f*(float(selected_b));
                int draw_b = int(float(selected_b)*(gray/draw_y));
                int draw_g = int(float(selected_g)*(gray/draw_y));
                int draw_r = int(float(selected_r)*(gray/draw_y));

                if(drawByReference)
                {
                    cv::circle(img, cv::Point2d(x, y), 1, cv::Scalar(blue, green, red), -1);
                }
                else
                {
                    cv::circle(img, cv::Point2d(x, y), 1, cv::Scalar(draw_b, draw_g, draw_r), -1);
                }
            }
        }
    }
}

double module(Point pt)
{
	return sqrt((double)pt.x*pt.x + pt.y*pt.y);
}

double distance(Point pt1, Point pt2)
{
	int dx = pt1.x - pt2.x;
	int dy = pt1.y - pt2.y;
	return sqrt((double)dx*dx + dy*dy);
}

double cross(Point pt1, Point pt2)
{
	return pt1.x*pt2.x + pt1.y*pt2.y;
}

double angle(Point pt1, Point pt2)
{
	return acos(cross(pt1, pt2) / (module(pt1)*module(pt2) + DBL_EPSILON));
}

// p or c is the center
int inCircle(Point p, Point c, int r)
{
	int dx = p.x - c.x;
	int dy = p.y - c.y;
	return dx*dx + dy*dy <= r*r ? 1 : 0;

}

//draw the hsv-plate
void createPlate(Mat &im1, int radius)
{
	Mat hsvImag(Size(radius << 1, radius << 1), CV_8UC3, Scalar(0, 0, 255));
	int w = hsvImag.cols;
	int h = hsvImag.rows;
	int cx = w >> 1;
	int cy = h >> 1;
	Point pt1(cx, 0);

	for (int j = 0; j < w; j++)
	{
		for (int i = 0; i < h; i++)
		{
			Point pt2(j - cx, i - cy);
			if (inCircle(Point(0, 0), pt2, radius))
			{
				int theta = static_cast<int>(angle(pt1, pt2) * 180 / CV_PI);
				if (i > cx)
				{
					theta = -theta + 360;
				}
				hsvImag.at<Vec3b>(i, j)[0] = saturate_cast<uchar>(theta / 2);
				hsvImag.at<Vec3b>(i, j)[1] = saturate_cast<uchar>(module(pt2) / cx * 255);
				hsvImag.at<Vec3b>(i, j)[2] = 255;
			}
		}
	}


	cvtColor(hsvImag, im1, COLOR_HSV2BGR);
}


#endif