qrcode.cpp 44.4 KB
Newer Older
N
Nesterov Alexander 已提交
1 2 3 4 5 6 7 8 9
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.

#include "precomp.hpp"
#include "opencv2/objdetect.hpp"
A
Alexander Nesterov 已提交
10 11 12 13 14
#include "opencv2/calib3d.hpp"

#ifdef HAVE_QUIRC
#include "quirc.h"
#endif
N
Nesterov Alexander 已提交
15 16 17 18

#include <limits>
#include <cmath>
#include <iostream>
A
Alexander Nesterov 已提交
19
#include <queue>
N
Nesterov Alexander 已提交
20 21 22

namespace cv
{
23 24
using std::vector;

25
class QRDetect
N
Nesterov Alexander 已提交
26
{
27
public:
28
    void init(const Mat& src, double eps_vertical_ = 0.2, double eps_horizontal_ = 0.1);
N
Nesterov Alexander 已提交
29
    bool localization();
30
    bool computeTransformationPoints();
N
Nesterov Alexander 已提交
31 32
    Mat getBinBarcode() { return bin_barcode; }
    Mat getStraightBarcode() { return straight_barcode; }
33
    vector<Point2f> getTransformationPoints() { return transformation_points; }
A
Alexander Nesterov 已提交
34
    static Point2f intersectionLines(Point2f a1, Point2f a2, Point2f b1, Point2f b2);
35
protected:
36 37
    vector<Vec3d> searchHorizontalLines();
    vector<Point2f> separateVerticalLines(const vector<Vec3d> &list_lines);
38 39 40
    void fixationPoints(vector<Point2f> &local_point);
    vector<Point2f> getQuadrilateral(vector<Point2f> angle_list);
    bool testBypassRoute(vector<Point2f> hull, int start, int finish);
A
Alexander Nesterov 已提交
41
    inline double getCosVectors(Point2f a, Point2f b, Point2f c);
42

43
    Mat barcode, bin_barcode, resized_barcode, resized_bin_barcode, straight_barcode;
44
    vector<Point2f> localization_points, transformation_points;
45
    double eps_vertical, eps_horizontal, coeff_expansion;
46
    enum resize_direction { ZOOMING, SHRINKING, UNCHANGED } purpose;
N
Nesterov Alexander 已提交
47 48
};

49

50
void QRDetect::init(const Mat& src, double eps_vertical_, double eps_horizontal_)
N
Nesterov Alexander 已提交
51
{
A
Alexander Nesterov 已提交
52
    CV_TRACE_FUNCTION();
53
    CV_Assert(!src.empty());
54
    barcode = src.clone();
55
    const double min_side = std::min(src.size().width, src.size().height);
56 57
    if (min_side < 512.0)
    {
58
        purpose = ZOOMING;
59
        coeff_expansion = 512.0 / min_side;
60 61
        const int width  = cvRound(src.size().width  * coeff_expansion);
        const int height = cvRound(src.size().height  * coeff_expansion);
62
        Size new_size(width, height);
63
        resize(src, barcode, new_size, 0, 0, INTER_LINEAR);
64
    }
65 66 67 68 69 70 71 72 73
    else if (min_side > 512.0)
    {
        purpose = SHRINKING;
        coeff_expansion = min_side / 512.0;
        const int width  = cvRound(src.size().width  / coeff_expansion);
        const int height = cvRound(src.size().height  / coeff_expansion);
        Size new_size(width, height);
        resize(src, resized_barcode, new_size, 0, 0, INTER_AREA);
    }
74 75
    else
    {
76
        purpose = UNCHANGED;
77 78
        coeff_expansion = 1.0;
    }
79

N
Nesterov Alexander 已提交
80 81
    eps_vertical   = eps_vertical_;
    eps_horizontal = eps_horizontal_;
82
    adaptiveThreshold(barcode, bin_barcode, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 83, 2);
83
    adaptiveThreshold(resized_barcode, resized_bin_barcode, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 83, 2);
A
Alexander Nesterov 已提交
84

N
Nesterov Alexander 已提交
85 86
}

87
vector<Vec3d> QRDetect::searchHorizontalLines()
N
Nesterov Alexander 已提交
88
{
A
Alexander Nesterov 已提交
89
    CV_TRACE_FUNCTION();
90
    vector<Vec3d> result;
91 92 93 94
    const int height_bin_barcode = bin_barcode.rows;
    const int width_bin_barcode  = bin_barcode.cols;
    const size_t test_lines_size = 5;
    double test_lines[test_lines_size];
A
Alexander Nesterov 已提交
95
    vector<size_t> pixels_position;
96 97

    for (int y = 0; y < height_bin_barcode; y++)
N
Nesterov Alexander 已提交
98
    {
A
Alexander Nesterov 已提交
99
        pixels_position.clear();
100
        const uint8_t *bin_barcode_row = bin_barcode.ptr<uint8_t>(y);
N
Nesterov Alexander 已提交
101

102 103 104
        int pos = 0;
        for (; pos < width_bin_barcode; pos++) { if (bin_barcode_row[pos] == 0) break; }
        if (pos == width_bin_barcode) { continue; }
N
Nesterov Alexander 已提交
105

A
Alexander Nesterov 已提交
106 107 108
        pixels_position.push_back(pos);
        pixels_position.push_back(pos);
        pixels_position.push_back(pos);
N
Nesterov Alexander 已提交
109

110 111 112 113
        uint8_t future_pixel = 255;
        for (int x = pos; x < width_bin_barcode; x++)
        {
            if (bin_barcode_row[x] == future_pixel)
N
Nesterov Alexander 已提交
114
            {
115
                future_pixel = 255 - future_pixel;
A
Alexander Nesterov 已提交
116
                pixels_position.push_back(x);
N
Nesterov Alexander 已提交
117
            }
118
        }
A
Alexander Nesterov 已提交
119 120
        pixels_position.push_back(width_bin_barcode - 1);
        for (size_t i = 2; i < pixels_position.size() - 4; i+=2)
121 122 123 124 125 126
        {
            test_lines[0] = static_cast<double>(pixels_position[i - 1] - pixels_position[i - 2]);
            test_lines[1] = static_cast<double>(pixels_position[i    ] - pixels_position[i - 1]);
            test_lines[2] = static_cast<double>(pixels_position[i + 1] - pixels_position[i    ]);
            test_lines[3] = static_cast<double>(pixels_position[i + 2] - pixels_position[i + 1]);
            test_lines[4] = static_cast<double>(pixels_position[i + 3] - pixels_position[i + 2]);
N
Nesterov Alexander 已提交
127

128
            double length = 0.0, weight = 0.0;
N
Nesterov Alexander 已提交
129

130
            for (size_t j = 0; j < test_lines_size; j++) { length += test_lines[j]; }
N
Nesterov Alexander 已提交
131

132 133 134
            if (length == 0) { continue; }
            for (size_t j = 0; j < test_lines_size; j++)
            {
A
Alexander Nesterov 已提交
135 136
                if (j != 2) { weight += fabs((test_lines[j] / length) - 1.0/7.0); }
                else        { weight += fabs((test_lines[j] / length) - 3.0/7.0); }
137
            }
N
Nesterov Alexander 已提交
138

139 140 141 142 143 144 145
            if (weight < eps_vertical)
            {
                Vec3d line;
                line[0] = static_cast<double>(pixels_position[i - 2]);
                line[1] = y;
                line[2] = length;
                result.push_back(line);
N
Nesterov Alexander 已提交
146 147 148 149 150 151
            }
        }
    }
    return result;
}

152
vector<Point2f> QRDetect::separateVerticalLines(const vector<Vec3d> &list_lines)
N
Nesterov Alexander 已提交
153
{
A
Alexander Nesterov 已提交
154
    CV_TRACE_FUNCTION();
155
    vector<Vec3d> result;
156 157
    int temp_length;
    vector<Point2f> point2f_result;
158
    uint8_t next_pixel;
159
    vector<double> test_lines;
N
Nesterov Alexander 已提交
160

161

162
    for (int coeff_epsilon = 1; coeff_epsilon < 10; coeff_epsilon++)
N
Nesterov Alexander 已提交
163
    {
164 165 166
        result.clear();
        temp_length = 0;
        point2f_result.clear();
167

168 169 170 171
        for (size_t pnt = 0; pnt < list_lines.size(); pnt++)
        {
            const int x = cvRound(list_lines[pnt][0] + list_lines[pnt][2] * 0.5);
            const int y = cvRound(list_lines[pnt][1]);
N
Nesterov Alexander 已提交
172

173
            // --------------- Search vertical up-lines --------------- //
N
Nesterov Alexander 已提交
174

175 176 177 178
            test_lines.clear();
            uint8_t future_pixel_up = 255;

            for (int j = y; j < bin_barcode.rows - 1; j++)
N
Nesterov Alexander 已提交
179
            {
180 181 182 183 184 185 186 187 188
                next_pixel = bin_barcode.ptr<uint8_t>(j + 1)[x];
                temp_length++;
                if (next_pixel == future_pixel_up)
                {
                    future_pixel_up = 255 - future_pixel_up;
                    test_lines.push_back(temp_length);
                    temp_length = 0;
                    if (test_lines.size() == 3) { break; }
                }
N
Nesterov Alexander 已提交
189 190
            }

191
            // --------------- Search vertical down-lines --------------- //
N
Nesterov Alexander 已提交
192

193 194
            uint8_t future_pixel_down = 255;
            for (int j = y; j >= 1; j--)
N
Nesterov Alexander 已提交
195
            {
196 197 198 199 200 201 202 203 204
                next_pixel = bin_barcode.ptr<uint8_t>(j - 1)[x];
                temp_length++;
                if (next_pixel == future_pixel_down)
                {
                    future_pixel_down = 255 - future_pixel_down;
                    test_lines.push_back(temp_length);
                    temp_length = 0;
                    if (test_lines.size() == 6) { break; }
                }
N
Nesterov Alexander 已提交
205 206
            }

207
            // --------------- Compute vertical lines --------------- //
N
Nesterov Alexander 已提交
208

209 210 211
            if (test_lines.size() == 6)
            {
                double length = 0.0, weight = 0.0;
N
Nesterov Alexander 已提交
212

213
                for (size_t i = 0; i < test_lines.size(); i++) { length += test_lines[i]; }
N
Nesterov Alexander 已提交
214

215 216 217 218 219 220
                CV_Assert(length > 0);
                for (size_t i = 0; i < test_lines.size(); i++)
                {
                    if (i % 3 != 0) { weight += fabs((test_lines[i] / length) - 1.0/ 7.0); }
                    else            { weight += fabs((test_lines[i] / length) - 3.0/14.0); }
                }
N
Nesterov Alexander 已提交
221

222 223 224 225
                if(weight < eps_horizontal * coeff_epsilon)
                {
                    result.push_back(list_lines[pnt]);
                }
226
            }
N
Nesterov Alexander 已提交
227
        }
228 229 230 231 232 233 234 235
        if (result.size() > 2)
        {
            for (size_t i = 0; i < result.size(); i++)
            {
                point2f_result.push_back(
                      Point2f(static_cast<float>(result[i][0] + result[i][2] * 0.5),
                              static_cast<float>(result[i][1])));
            }
N
Nesterov Alexander 已提交
236

237 238 239 240 241 242 243 244 245
            vector<Point2f> centers;
            Mat labels;
            double compactness;
            compactness = kmeans(point2f_result, 3, labels,
                 TermCriteria( TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1),
                 3, KMEANS_PP_CENTERS, centers);
            if (compactness == 0) { continue; }
            if (compactness > 0)  { break; }
        }
N
Nesterov Alexander 已提交
246
    }
247
    return point2f_result;
N
Nesterov Alexander 已提交
248 249
}

250
void QRDetect::fixationPoints(vector<Point2f> &local_point)
N
Nesterov Alexander 已提交
251
{
A
Alexander Nesterov 已提交
252
    CV_TRACE_FUNCTION();
N
Nesterov Alexander 已提交
253 254 255 256 257 258
    double cos_angles[3], norm_triangl[3];

    norm_triangl[0] = norm(local_point[1] - local_point[2]);
    norm_triangl[1] = norm(local_point[0] - local_point[2]);
    norm_triangl[2] = norm(local_point[1] - local_point[0]);

259 260 261 262 263 264 265 266 267 268 269 270 271
    cos_angles[0] = (norm_triangl[1] * norm_triangl[1] + norm_triangl[2] * norm_triangl[2]
                  -  norm_triangl[0] * norm_triangl[0]) / (2 * norm_triangl[1] * norm_triangl[2]);
    cos_angles[1] = (norm_triangl[0] * norm_triangl[0] + norm_triangl[2] * norm_triangl[2]
                  -  norm_triangl[1] * norm_triangl[1]) / (2 * norm_triangl[0] * norm_triangl[2]);
    cos_angles[2] = (norm_triangl[0] * norm_triangl[0] + norm_triangl[1] * norm_triangl[1]
                  -  norm_triangl[2] * norm_triangl[2]) / (2 * norm_triangl[0] * norm_triangl[1]);

    const double angle_barrier = 0.85;
    if (fabs(cos_angles[0]) > angle_barrier || fabs(cos_angles[1]) > angle_barrier || fabs(cos_angles[2]) > angle_barrier)
    {
        local_point.clear();
        return;
    }
272 273

    size_t i_min_cos =
274 275
       (cos_angles[0] < cos_angles[1] && cos_angles[0] < cos_angles[2]) ? 0 :
       (cos_angles[1] < cos_angles[0] && cos_angles[1] < cos_angles[2]) ? 1 : 2;
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
    size_t index_max = 0;
    double max_area = std::numeric_limits<double>::min();
    for (size_t i = 0; i < local_point.size(); i++)
    {
        const size_t current_index = i % 3;
        const size_t left_index  = (i + 1) % 3;
        const size_t right_index = (i + 2) % 3;

        const Point2f current_point(local_point[current_index]),
            left_point(local_point[left_index]), right_point(local_point[right_index]),
            central_point(intersectionLines(current_point,
                              Point2f(static_cast<float>((local_point[left_index].x + local_point[right_index].x) * 0.5),
                                      static_cast<float>((local_point[left_index].y + local_point[right_index].y) * 0.5)),
                              Point2f(0, static_cast<float>(bin_barcode.rows - 1)),
                              Point2f(static_cast<float>(bin_barcode.cols - 1),
                                      static_cast<float>(bin_barcode.rows - 1))));


        vector<Point2f> list_area_pnt;
        list_area_pnt.push_back(current_point);

        vector<LineIterator> list_line_iter;
        list_line_iter.push_back(LineIterator(bin_barcode, current_point, left_point));
        list_line_iter.push_back(LineIterator(bin_barcode, current_point, central_point));
        list_line_iter.push_back(LineIterator(bin_barcode, current_point, right_point));
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
        for (size_t k = 0; k < list_line_iter.size(); k++)
        {
            uint8_t future_pixel = 255, count_index = 0;
            for(int j = 0; j < list_line_iter[k].count; j++, ++list_line_iter[k])
            {
                if (list_line_iter[k].pos().x >= bin_barcode.cols ||
                    list_line_iter[k].pos().y >= bin_barcode.rows) { break; }
                const uint8_t value = bin_barcode.at<uint8_t>(list_line_iter[k].pos());
                if (value == future_pixel)
                {
                    future_pixel = 255 - future_pixel;
                    count_index++;
                    if (count_index == 3)
                    {
                        list_area_pnt.push_back(list_line_iter[k].pos());
                        break;
                    }
                }
            }
        }

        const double temp_check_area = contourArea(list_area_pnt);
        if (temp_check_area > max_area)
        {
            index_max = current_index;
            max_area = temp_check_area;
        }

    }
    if (index_max == i_min_cos) { std::swap(local_point[0], local_point[index_max]); }
    else { local_point.clear(); return; }

    const Point2f rpt = local_point[0], bpt = local_point[1], gpt = local_point[2];
336 337
    Matx22f m(rpt.x - bpt.x, rpt.y - bpt.y, gpt.x - rpt.x, gpt.y - rpt.y);
    if( determinant(m) > 0 )
N
Nesterov Alexander 已提交
338
    {
339
        std::swap(local_point[1], local_point[2]);
N
Nesterov Alexander 已提交
340 341 342
    }
}

343
bool QRDetect::localization()
N
Nesterov Alexander 已提交
344
{
A
Alexander Nesterov 已提交
345
    CV_TRACE_FUNCTION();
346
    Point2f begin, end;
347
    vector<Vec3d> list_lines_x = searchHorizontalLines();
348
    if( list_lines_x.empty() ) { return false; }
349
    vector<Point2f> list_lines_y = separateVerticalLines(list_lines_x);
350
    if( list_lines_y.empty() ) { return false; }
351 352 353 354

    vector<Point2f> centers;
    Mat labels;
    kmeans(list_lines_y, 3, labels,
355
           TermCriteria( TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1),
356 357 358
           3, KMEANS_PP_CENTERS, localization_points);

    fixationPoints(localization_points);
N
Nesterov Alexander 已提交
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
    bool suare_flag = false, local_points_flag = false;
    double triangle_sides[3];
    triangle_sides[0] = norm(localization_points[0] - localization_points[1]);
    triangle_sides[1] = norm(localization_points[1] - localization_points[2]);
    triangle_sides[2] = norm(localization_points[2] - localization_points[0]);

    double triangle_perim = (triangle_sides[0] + triangle_sides[1] + triangle_sides[2]) / 2;

    double square_area = sqrt((triangle_perim * (triangle_perim - triangle_sides[0])
                                              * (triangle_perim - triangle_sides[1])
                                              * (triangle_perim - triangle_sides[2]))) * 2;
    double img_square_area = bin_barcode.cols * bin_barcode.rows;

    if (square_area > (img_square_area * 0.2))
    {
        suare_flag = true;
    }
    if (localization_points.size() != 3)
    {
        local_points_flag = true;
    }
    if ((suare_flag || local_points_flag) && purpose == SHRINKING)
    {
        localization_points.clear();
        bin_barcode = resized_bin_barcode.clone();
        list_lines_x = searchHorizontalLines();
        if( list_lines_x.empty() ) { return false; }
        list_lines_y = separateVerticalLines(list_lines_x);
        if( list_lines_y.empty() ) { return false; }

        kmeans(list_lines_y, 3, labels,
               TermCriteria( TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1),
               3, KMEANS_PP_CENTERS, localization_points);

        fixationPoints(localization_points);
        if (localization_points.size() != 3) { return false; }

        const int width  = cvRound(bin_barcode.size().width  * coeff_expansion);
        const int height = cvRound(bin_barcode.size().height * coeff_expansion);
        Size new_size(width, height);
        Mat intermediate;
        resize(bin_barcode, intermediate, new_size, 0, 0, INTER_LINEAR);
        bin_barcode = intermediate.clone();
        for (size_t i = 0; i < localization_points.size(); i++)
        {
            localization_points[i] *= coeff_expansion;
        }
    }
    if (purpose == ZOOMING)
N
Nesterov Alexander 已提交
409
    {
410 411
        const int width  = cvRound(bin_barcode.size().width  / coeff_expansion);
        const int height = cvRound(bin_barcode.size().height / coeff_expansion);
412
        Size new_size(width, height);
413
        Mat intermediate;
414
        resize(bin_barcode, intermediate, new_size, 0, 0, INTER_LINEAR);
415 416 417 418 419
        bin_barcode = intermediate.clone();
        for (size_t i = 0; i < localization_points.size(); i++)
        {
            localization_points[i] /= coeff_expansion;
        }
N
Nesterov Alexander 已提交
420 421
    }

422 423 424 425 426 427 428 429 430 431
    for (size_t i = 0; i < localization_points.size(); i++)
    {
        for (size_t j = i + 1; j < localization_points.size(); j++)
        {
            if (norm(localization_points[i] - localization_points[j]) < 10)
            {
                return false;
            }
        }
    }
N
Nesterov Alexander 已提交
432
    return true;
433

N
Nesterov Alexander 已提交
434 435
}

436
bool QRDetect::computeTransformationPoints()
N
Nesterov Alexander 已提交
437
{
A
Alexander Nesterov 已提交
438
    CV_TRACE_FUNCTION();
439
    if (localization_points.size() != 3) { return false; }
N
Nesterov Alexander 已提交
440

441 442 443
    vector<Point> locations, non_zero_elem[3], newHull;
    vector<Point2f> new_non_zero_elem[3];
    for (size_t i = 0; i < 3; i++)
N
Nesterov Alexander 已提交
444
    {
445 446
        Mat mask = Mat::zeros(bin_barcode.rows + 2, bin_barcode.cols + 2, CV_8UC1);
        uint8_t next_pixel, future_pixel = 255;
447
        int count_test_lines = 0, index = cvRound(localization_points[i].x);
448
        for (; index < bin_barcode.cols - 1; index++)
N
Nesterov Alexander 已提交
449
        {
A
Alexander Nesterov 已提交
450
            next_pixel = bin_barcode.ptr<uint8_t>(cvRound(localization_points[i].y))[index + 1];
451
            if (next_pixel == future_pixel)
N
Nesterov Alexander 已提交
452
            {
453 454 455
                future_pixel = 255 - future_pixel;
                count_test_lines++;
                if (count_test_lines == 2)
N
Nesterov Alexander 已提交
456
                {
457
                    floodFill(bin_barcode, mask,
458
                              Point(index + 1, cvRound(localization_points[i].y)), 255,
459 460
                              0, Scalar(), Scalar(), FLOODFILL_MASK_ONLY);
                    break;
N
Nesterov Alexander 已提交
461 462 463
                }
            }
        }
464 465 466 467
        Mat mask_roi = mask(Range(1, bin_barcode.rows - 1), Range(1, bin_barcode.cols - 1));
        findNonZero(mask_roi, non_zero_elem[i]);
        newHull.insert(newHull.end(), non_zero_elem[i].begin(), non_zero_elem[i].end());
    }
S
Suleyman TURKMEN 已提交
468
    convexHull(newHull, locations);
469 470 471
    for (size_t i = 0; i < locations.size(); i++)
    {
        for (size_t j = 0; j < 3; j++)
N
Nesterov Alexander 已提交
472
        {
473 474 475 476 477 478 479
            for (size_t k = 0; k < non_zero_elem[j].size(); k++)
            {
                if (locations[i] == non_zero_elem[j][k])
                {
                    new_non_zero_elem[j].push_back(locations[i]);
                }
            }
N
Nesterov Alexander 已提交
480 481 482
        }
    }

483 484 485
    double pentagon_diag_norm = -1;
    Point2f down_left_edge_point, up_right_edge_point, up_left_edge_point;
    for (size_t i = 0; i < new_non_zero_elem[1].size(); i++)
N
Nesterov Alexander 已提交
486
    {
487
        for (size_t j = 0; j < new_non_zero_elem[2].size(); j++)
N
Nesterov Alexander 已提交
488
        {
489 490 491 492 493 494 495
            double temp_norm = norm(new_non_zero_elem[1][i] - new_non_zero_elem[2][j]);
            if (temp_norm > pentagon_diag_norm)
            {
                down_left_edge_point = new_non_zero_elem[1][i];
                up_right_edge_point  = new_non_zero_elem[2][j];
                pentagon_diag_norm = temp_norm;
            }
N
Nesterov Alexander 已提交
496 497
        }
    }
A
Alexander Nesterov 已提交
498

499
    if (down_left_edge_point == Point2f(0, 0) ||
A
Alexander Nesterov 已提交
500 501
        up_right_edge_point  == Point2f(0, 0) ||
        new_non_zero_elem[0].size() == 0) { return false; }
N
Nesterov Alexander 已提交
502

503 504
    double max_area = -1;
    up_left_edge_point = new_non_zero_elem[0][0];
A
Alexander Nesterov 已提交
505

506 507
    for (size_t i = 0; i < new_non_zero_elem[0].size(); i++)
    {
A
Alexander Nesterov 已提交
508 509 510 511 512
        vector<Point2f> list_edge_points;
        list_edge_points.push_back(new_non_zero_elem[0][i]);
        list_edge_points.push_back(down_left_edge_point);
        list_edge_points.push_back(up_right_edge_point);

A
Alexander Nesterov 已提交
513
        double temp_area = fabs(contourArea(list_edge_points));
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        if (max_area < temp_area)
        {
            up_left_edge_point = new_non_zero_elem[0][i];
            max_area = temp_area;
        }
    }

    Point2f down_max_delta_point, up_max_delta_point;
    double norm_down_max_delta = -1, norm_up_max_delta = -1;
    for (size_t i = 0; i < new_non_zero_elem[1].size(); i++)
    {
        double temp_norm_delta = norm(up_left_edge_point - new_non_zero_elem[1][i])
                               + norm(down_left_edge_point - new_non_zero_elem[1][i]);
        if (norm_down_max_delta < temp_norm_delta)
        {
            down_max_delta_point = new_non_zero_elem[1][i];
            norm_down_max_delta = temp_norm_delta;
        }
    }

A
Alexander Nesterov 已提交
534

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    for (size_t i = 0; i < new_non_zero_elem[2].size(); i++)
    {
        double temp_norm_delta = norm(up_left_edge_point - new_non_zero_elem[2][i])
                               + norm(up_right_edge_point - new_non_zero_elem[2][i]);
        if (norm_up_max_delta < temp_norm_delta)
        {
            up_max_delta_point = new_non_zero_elem[2][i];
            norm_up_max_delta = temp_norm_delta;
        }
    }

    transformation_points.push_back(down_left_edge_point);
    transformation_points.push_back(up_left_edge_point);
    transformation_points.push_back(up_right_edge_point);
    transformation_points.push_back(
        intersectionLines(down_left_edge_point, down_max_delta_point,
                          up_right_edge_point, up_max_delta_point));

    vector<Point2f> quadrilateral = getQuadrilateral(transformation_points);
    transformation_points = quadrilateral;

556 557 558 559 560 561 562
    int width = bin_barcode.size().width;
    int height = bin_barcode.size().height;
    for (size_t i = 0; i < transformation_points.size(); i++)
    {
        if ((cvRound(transformation_points[i].x) > width) ||
            (cvRound(transformation_points[i].y) > height)) { return false; }
    }
563
    return true;
N
Nesterov Alexander 已提交
564 565
}

566
Point2f QRDetect::intersectionLines(Point2f a1, Point2f a2, Point2f b1, Point2f b2)
N
Nesterov Alexander 已提交
567
{
568 569 570 571 572 573 574 575 576 577
    Point2f result_square_angle(
                              ((a1.x * a2.y  -  a1.y * a2.x) * (b1.x - b2.x) -
                               (b1.x * b2.y  -  b1.y * b2.x) * (a1.x - a2.x)) /
                              ((a1.x - a2.x) * (b1.y - b2.y) -
                               (a1.y - a2.y) * (b1.x - b2.x)),
                              ((a1.x * a2.y  -  a1.y * a2.x) * (b1.y - b2.y) -
                               (b1.x * b2.y  -  b1.y * b2.x) * (a1.y - a2.y)) /
                              ((a1.x - a2.x) * (b1.y - b2.y) -
                               (a1.y - a2.y) * (b1.x - b2.x))
                              );
N
Nesterov Alexander 已提交
578 579 580
    return result_square_angle;
}

581
// test function (if true then ------> else <------ )
582
bool QRDetect::testBypassRoute(vector<Point2f> hull, int start, int finish)
583
{
A
Alexander Nesterov 已提交
584
    CV_TRACE_FUNCTION();
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    int index_hull = start, next_index_hull, hull_size = (int)hull.size();
    double test_length[2] = { 0.0, 0.0 };
    do
    {
        next_index_hull = index_hull + 1;
        if (next_index_hull == hull_size) { next_index_hull = 0; }
        test_length[0] += norm(hull[index_hull] - hull[next_index_hull]);
        index_hull = next_index_hull;
    }
    while(index_hull != finish);

    index_hull = start;
    do
    {
        next_index_hull = index_hull - 1;
        if (next_index_hull == -1) { next_index_hull = hull_size - 1; }
        test_length[1] += norm(hull[index_hull] - hull[next_index_hull]);
        index_hull = next_index_hull;
    }
    while(index_hull != finish);

    if (test_length[0] < test_length[1]) { return true; } else { return false; }
}

609
vector<Point2f> QRDetect::getQuadrilateral(vector<Point2f> angle_list)
N
Nesterov Alexander 已提交
610
{
A
Alexander Nesterov 已提交
611
    CV_TRACE_FUNCTION();
N
Nesterov Alexander 已提交
612 613
    size_t angle_size = angle_list.size();
    uint8_t value, mask_value;
614 615
    Mat mask = Mat::zeros(bin_barcode.rows + 2, bin_barcode.cols + 2, CV_8UC1);
    Mat fill_bin_barcode = bin_barcode.clone();
N
Nesterov Alexander 已提交
616 617 618 619 620 621 622 623 624 625
    for (size_t i = 0; i < angle_size; i++)
    {
        LineIterator line_iter(bin_barcode, angle_list[ i      % angle_size],
                                            angle_list[(i + 1) % angle_size]);
        for(int j = 0; j < line_iter.count; j++, ++line_iter)
        {
            value = bin_barcode.at<uint8_t>(line_iter.pos());
            mask_value = mask.at<uint8_t>(line_iter.pos() + Point(1, 1));
            if (value == 0 && mask_value == 0)
            {
626 627
                floodFill(fill_bin_barcode, mask, line_iter.pos(), 255,
                          0, Scalar(), Scalar(), FLOODFILL_MASK_ONLY);
N
Nesterov Alexander 已提交
628 629 630
            }
        }
    }
631 632
    vector<Point> locations;
    Mat mask_roi = mask(Range(1, bin_barcode.rows - 1), Range(1, bin_barcode.cols - 1));
N
Nesterov Alexander 已提交
633

A
Alexander Nesterov 已提交
634
    findNonZero(mask_roi, locations);
N
Nesterov Alexander 已提交
635 636 637

    for (size_t i = 0; i < angle_list.size(); i++)
    {
638 639
        int x = cvRound(angle_list[i].x);
        int y = cvRound(angle_list[i].y);
640
        locations.push_back(Point(x, y));
N
Nesterov Alexander 已提交
641 642
    }

643
    vector<Point> integer_hull;
S
Suleyman TURKMEN 已提交
644
    convexHull(locations, integer_hull);
645 646 647
    int hull_size = (int)integer_hull.size();
    vector<Point2f> hull(hull_size);
    for (int i = 0; i < hull_size; i++)
N
Nesterov Alexander 已提交
648
    {
649 650
        float x = saturate_cast<float>(integer_hull[i].x);
        float y = saturate_cast<float>(integer_hull[i].y);
651
        hull[i] = Point2f(x, y);
N
Nesterov Alexander 已提交
652 653
    }

A
Alexander Nesterov 已提交
654
    const double experimental_area = fabs(contourArea(hull));
655

656 657
    vector<Point2f> result_hull_point(angle_size);
    double min_norm;
N
Nesterov Alexander 已提交
658 659 660 661
    for (size_t i = 0; i < angle_size; i++)
    {
        min_norm = std::numeric_limits<double>::max();
        Point closest_pnt;
662
        for (int j = 0; j < hull_size; j++)
N
Nesterov Alexander 已提交
663
        {
664 665
            double temp_norm = norm(hull[j] - angle_list[i]);
            if (min_norm > temp_norm)
N
Nesterov Alexander 已提交
666
            {
667 668
                min_norm = temp_norm;
                closest_pnt = hull[j];
N
Nesterov Alexander 已提交
669 670 671 672 673
            }
        }
        result_hull_point[i] = closest_pnt;
    }

674
    int start_line[2] = { 0, 0 }, finish_line[2] = { 0, 0 }, unstable_pnt = 0;
N
Nesterov Alexander 已提交
675 676
    for (int i = 0; i < hull_size; i++)
    {
677 678 679 680
        if (result_hull_point[2] == hull[i]) { start_line[0] = i; }
        if (result_hull_point[1] == hull[i]) { finish_line[0] = start_line[1] = i; }
        if (result_hull_point[0] == hull[i]) { finish_line[1] = i; }
        if (result_hull_point[3] == hull[i]) { unstable_pnt = i; }
N
Nesterov Alexander 已提交
681 682
    }

683
    int index_hull, extra_index_hull, next_index_hull, extra_next_index_hull;
N
Nesterov Alexander 已提交
684 685
    Point result_side_begin[4], result_side_end[4];

686 687
    bool bypass_orientation = testBypassRoute(hull, start_line[0], finish_line[0]);

N
Nesterov Alexander 已提交
688 689 690 691
    min_norm = std::numeric_limits<double>::max();
    index_hull = start_line[0];
    do
    {
692
        if (bypass_orientation) { next_index_hull = index_hull + 1; }
N
Nesterov Alexander 已提交
693 694 695 696 697
        else { next_index_hull = index_hull - 1; }

        if (next_index_hull == hull_size) { next_index_hull = 0; }
        if (next_index_hull == -1) { next_index_hull = hull_size - 1; }

698 699
        Point angle_closest_pnt =  norm(hull[index_hull] - angle_list[1]) >
        norm(hull[index_hull] - angle_list[2]) ? angle_list[2] : angle_list[1];
N
Nesterov Alexander 已提交
700 701

        Point intrsc_line_hull =
702 703 704
        intersectionLines(hull[index_hull], hull[next_index_hull],
                          angle_list[1], angle_list[2]);
        double temp_norm = getCosVectors(hull[index_hull], intrsc_line_hull, angle_closest_pnt);
N
Nesterov Alexander 已提交
705
        if (min_norm > temp_norm &&
706
            norm(hull[index_hull] - hull[next_index_hull]) >
A
Alexander Nesterov 已提交
707
            norm(angle_list[1] - angle_list[2]) * 0.1)
N
Nesterov Alexander 已提交
708 709
        {
            min_norm = temp_norm;
710 711
            result_side_begin[0] = hull[index_hull];
            result_side_end[0]   = hull[next_index_hull];
N
Nesterov Alexander 已提交
712 713 714 715 716 717 718 719 720
        }


        index_hull = next_index_hull;
    }
    while(index_hull != finish_line[0]);

    if (min_norm == std::numeric_limits<double>::max())
    {
721 722
        result_side_begin[0] = angle_list[1];
        result_side_end[0]   = angle_list[2];
N
Nesterov Alexander 已提交
723 724 725 726
    }

    min_norm = std::numeric_limits<double>::max();
    index_hull = start_line[1];
727
    bypass_orientation = testBypassRoute(hull, start_line[1], finish_line[1]);
N
Nesterov Alexander 已提交
728 729
    do
    {
730
        if (bypass_orientation) { next_index_hull = index_hull + 1; }
N
Nesterov Alexander 已提交
731 732 733 734 735
        else { next_index_hull = index_hull - 1; }

        if (next_index_hull == hull_size) { next_index_hull = 0; }
        if (next_index_hull == -1) { next_index_hull = hull_size - 1; }

736 737
        Point angle_closest_pnt =  norm(hull[index_hull] - angle_list[0]) >
        norm(hull[index_hull] - angle_list[1]) ? angle_list[1] : angle_list[0];
N
Nesterov Alexander 已提交
738 739

        Point intrsc_line_hull =
740 741 742
        intersectionLines(hull[index_hull], hull[next_index_hull],
                          angle_list[0], angle_list[1]);
        double temp_norm = getCosVectors(hull[index_hull], intrsc_line_hull, angle_closest_pnt);
N
Nesterov Alexander 已提交
743
        if (min_norm > temp_norm &&
744
            norm(hull[index_hull] - hull[next_index_hull]) >
A
Alexander Nesterov 已提交
745
            norm(angle_list[0] - angle_list[1]) * 0.05)
N
Nesterov Alexander 已提交
746 747
        {
            min_norm = temp_norm;
748 749
            result_side_begin[1] = hull[index_hull];
            result_side_end[1]   = hull[next_index_hull];
N
Nesterov Alexander 已提交
750 751 752 753 754 755 756 757
        }

        index_hull = next_index_hull;
    }
    while(index_hull != finish_line[1]);

    if (min_norm == std::numeric_limits<double>::max())
    {
758 759
        result_side_begin[1] = angle_list[0];
        result_side_end[1]   = angle_list[1];
N
Nesterov Alexander 已提交
760 761
    }

762
    bypass_orientation = testBypassRoute(hull, start_line[0], unstable_pnt);
763
    const bool extra_bypass_orientation = testBypassRoute(hull, finish_line[1], unstable_pnt);
N
Nesterov Alexander 已提交
764

765
    vector<Point2f> result_angle_list(4), test_result_angle_list(4);
766
    double min_diff_area = std::numeric_limits<double>::max();
N
Nesterov Alexander 已提交
767
    index_hull = start_line[0];
768
    const double standart_norm = std::max(
769 770
        norm(result_side_begin[0] - result_side_end[0]),
        norm(result_side_begin[1] - result_side_end[1]));
N
Nesterov Alexander 已提交
771 772
    do
    {
773
        if (bypass_orientation) { next_index_hull = index_hull + 1; }
N
Nesterov Alexander 已提交
774 775 776 777 778
        else { next_index_hull = index_hull - 1; }

        if (next_index_hull == hull_size) { next_index_hull = 0; }
        if (next_index_hull == -1) { next_index_hull = hull_size - 1; }

A
Alexander Nesterov 已提交
779
        if (norm(hull[index_hull] - hull[next_index_hull]) < standart_norm * 0.1)
780 781
        { index_hull = next_index_hull; continue; }

N
Nesterov Alexander 已提交
782 783 784
        extra_index_hull = finish_line[1];
        do
        {
785
            if (extra_bypass_orientation) { extra_next_index_hull = extra_index_hull + 1; }
N
Nesterov Alexander 已提交
786 787 788 789 790
            else { extra_next_index_hull = extra_index_hull - 1; }

            if (extra_next_index_hull == hull_size) { extra_next_index_hull = 0; }
            if (extra_next_index_hull == -1) { extra_next_index_hull = hull_size - 1; }

A
Alexander Nesterov 已提交
791
            if (norm(hull[extra_index_hull] - hull[extra_next_index_hull]) < standart_norm * 0.1)
792 793
            { extra_index_hull = extra_next_index_hull; continue; }

N
Nesterov Alexander 已提交
794
            test_result_angle_list[0]
795 796
            = intersectionLines(result_side_begin[0], result_side_end[0],
                                result_side_begin[1], result_side_end[1]);
N
Nesterov Alexander 已提交
797
            test_result_angle_list[1]
798 799
            = intersectionLines(result_side_begin[1], result_side_end[1],
                                hull[extra_index_hull], hull[extra_next_index_hull]);
N
Nesterov Alexander 已提交
800
            test_result_angle_list[2]
801 802
            = intersectionLines(hull[extra_index_hull], hull[extra_next_index_hull],
                                hull[index_hull], hull[next_index_hull]);
N
Nesterov Alexander 已提交
803
            test_result_angle_list[3]
804 805 806
            = intersectionLines(hull[index_hull], hull[next_index_hull],
                                result_side_begin[0], result_side_end[0]);

807 808
            const double test_diff_area
                = fabs(fabs(contourArea(test_result_angle_list)) - experimental_area);
809
            if (min_diff_area > test_diff_area)
N
Nesterov Alexander 已提交
810
            {
811
                min_diff_area = test_diff_area;
N
Nesterov Alexander 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824
                for (size_t i = 0; i < test_result_angle_list.size(); i++)
                {
                    result_angle_list[i] = test_result_angle_list[i];
                }
            }

            extra_index_hull = extra_next_index_hull;
        }
        while(extra_index_hull != unstable_pnt);

        index_hull = next_index_hull;
    }
    while(index_hull != unstable_pnt);
A
Alexander Nesterov 已提交
825

826
    // check label points
A
Alexander Nesterov 已提交
827 828 829 830
    if (norm(result_angle_list[0] - angle_list[1]) > 2) { result_angle_list[0] = angle_list[1]; }
    if (norm(result_angle_list[1] - angle_list[0]) > 2) { result_angle_list[1] = angle_list[0]; }
    if (norm(result_angle_list[3] - angle_list[2]) > 2) { result_angle_list[3] = angle_list[2]; }

831 832 833 834 835 836
    // check calculation point
    if (norm(result_angle_list[2] - angle_list[3]) >
       (norm(result_angle_list[0] - result_angle_list[1]) +
        norm(result_angle_list[0] - result_angle_list[3])) * 0.5 )
    { result_angle_list[2] = angle_list[3]; }

N
Nesterov Alexander 已提交
837 838 839 840 841 842 843 844
    return result_angle_list;
}

//      / | b
//     /  |
//    /   |
//  a/    | c

845
inline double QRDetect::getCosVectors(Point2f a, Point2f b, Point2f c)
N
Nesterov Alexander 已提交
846
{
A
Alexander Nesterov 已提交
847
    return ((a - b).x * (c - b).x + (a - b).y * (c - b).y) / (norm(a - b) * norm(c - b));
N
Nesterov Alexander 已提交
848 849
}

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
struct QRCodeDetector::Impl
{
public:
    Impl() { epsX = 0.2; epsY = 0.1; }
    ~Impl() {}

    double epsX, epsY;
};

QRCodeDetector::QRCodeDetector() : p(new Impl) {}
QRCodeDetector::~QRCodeDetector() {}

void QRCodeDetector::setEpsX(double epsX) { p->epsX = epsX; }
void QRCodeDetector::setEpsY(double epsY) { p->epsY = epsY; }

bool QRCodeDetector::detect(InputArray in, OutputArray points) const
{
    Mat inarr = in.getMat();
    CV_Assert(!inarr.empty());
869
    CV_Assert(inarr.depth() == CV_8U);
870 871 872
    if (inarr.cols <= 20 || inarr.rows <= 20)
        return false;  // image data is not enough for providing reliable results

873 874 875 876 877 878 879 880
    int incn = inarr.channels();
    if( incn == 3 || incn == 4 )
    {
        Mat gray;
        cvtColor(inarr, gray, COLOR_BGR2GRAY);
        inarr = gray;
    }

881 882 883 884 885
    QRDetect qrdet;
    qrdet.init(inarr, p->epsX, p->epsY);
    if (!qrdet.localization()) { return false; }
    if (!qrdet.computeTransformationPoints()) { return false; }
    vector<Point2f> pnts2f = qrdet.getTransformationPoints();
886
    Mat(pnts2f).convertTo(points, points.fixedType() ? points.type() : CV_32FC2);
N
Nesterov Alexander 已提交
887 888 889
    return true;
}

890
bool detectQRCode(InputArray in, vector<Point> &points, double eps_x, double eps_y)
891 892 893 894 895 896 897 898
{
    QRCodeDetector qrdetector;
    qrdetector.setEpsX(eps_x);
    qrdetector.setEpsY(eps_y);

    return qrdetector.detect(in, points);
}

A
Alexander Nesterov 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
class QRDecode
{
public:
    void init(const Mat &src, const vector<Point2f> &points);
    Mat getIntermediateBarcode() { return intermediate; }
    Mat getStraightBarcode() { return straight; }
    size_t getVersion() { return version; }
    std::string getDecodeInformation() { return result_info; }
    bool fullDecodingProcess();
protected:
    bool updatePerspective();
    bool versionDefinition();
    bool samplingForVersion();
    bool decodingProcess();
    Mat original, no_border_intermediate, intermediate, straight;
    vector<Point2f> original_points;
    std::string result_info;
    uint8_t version, version_size;
    float test_perspective_size;
};

void QRDecode::init(const Mat &src, const vector<Point2f> &points)
{
A
Alexander Nesterov 已提交
922
    CV_TRACE_FUNCTION();
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    vector<Point2f> bbox = points;
    double coeff_expansion;
    const int min_side = std::min(src.size().width, src.size().height);
    if (min_side > 512)
    {
        coeff_expansion = min_side / 512;
        const int width  = cvRound(src.size().width  / coeff_expansion);
        const int height = cvRound(src.size().height / coeff_expansion);
        Size new_size(width, height);
        resize(src, original, new_size, 0, 0, INTER_AREA);
            for (size_t i = 0; i < bbox.size(); i++)
            {
                bbox[i] /= static_cast<float>(coeff_expansion);
            }
    }
    else
    {
        original = src.clone();
    }
    intermediate = Mat::zeros(original.size(), CV_8UC1);
    original_points = bbox;
A
Alexander Nesterov 已提交
944 945 946 947 948 949 950 951
    version = 0;
    version_size = 0;
    test_perspective_size = 251;
    result_info = "";
}

bool QRDecode::updatePerspective()
{
A
Alexander Nesterov 已提交
952
    CV_TRACE_FUNCTION();
953 954 955 956 957
    const Point2f centerPt = QRDetect::intersectionLines(original_points[0], original_points[2],
                                                         original_points[1], original_points[3]);
    if (cvIsNaN(centerPt.x) || cvIsNaN(centerPt.y))
        return false;

A
Alexander Nesterov 已提交
958 959 960 961 962 963 964 965 966
    const Size temporary_size(cvRound(test_perspective_size), cvRound(test_perspective_size));

    vector<Point2f> perspective_points;
    perspective_points.push_back(Point2f(0.f, 0.f));
    perspective_points.push_back(Point2f(test_perspective_size, 0.f));

    perspective_points.push_back(Point2f(test_perspective_size, test_perspective_size));
    perspective_points.push_back(Point2f(0.f, test_perspective_size));

967 968 969 970 971 972 973
    perspective_points.push_back(Point2f(test_perspective_size * 0.5f, test_perspective_size * 0.5f));

    vector<Point2f> pts = original_points;
    pts.push_back(centerPt);

    Mat H = findHomography(pts, perspective_points);
    Mat bin_original;
A
Alexander Nesterov 已提交
974
    adaptiveThreshold(original, bin_original, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 83, 2);
975
    Mat temp_intermediate;
A
Alexander Nesterov 已提交
976 977 978 979 980 981 982 983 984
    warpPerspective(bin_original, temp_intermediate, H, temporary_size, INTER_NEAREST);
    no_border_intermediate = temp_intermediate(Range(1, temp_intermediate.rows), Range(1, temp_intermediate.cols));

    const int border = cvRound(0.1 * test_perspective_size);
    const int borderType = BORDER_CONSTANT;
    copyMakeBorder(no_border_intermediate, intermediate, border, border, border, border, borderType, Scalar(255));
    return true;
}

985 986 987 988 989 990 991 992 993 994 995 996 997 998
inline Point computeOffset(const vector<Point>& v)
{
    // compute the width/height of convex hull
    Rect areaBox = boundingRect(v);

    // compute the good offset
    // the box is consisted by 7 steps
    // to pick the middle of the stripe, it needs to be 1/14 of the size
    const int cStep = 7 * 2;
    Point offset = Point(areaBox.width, areaBox.height);
    offset /= cStep;
    return offset;
}

A
Alexander Nesterov 已提交
999 1000
bool QRDecode::versionDefinition()
{
A
Alexander Nesterov 已提交
1001
    CV_TRACE_FUNCTION();
A
Alexander Nesterov 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    LineIterator line_iter(intermediate, Point2f(0, 0), Point2f(test_perspective_size, test_perspective_size));
    Point black_point = Point(0, 0);
    for(int j = 0; j < line_iter.count; j++, ++line_iter)
    {
        const uint8_t value = intermediate.at<uint8_t>(line_iter.pos());
        if (value == 0) { black_point = line_iter.pos(); break; }
    }

    Mat mask = Mat::zeros(intermediate.rows + 2, intermediate.cols + 2, CV_8UC1);
    floodFill(intermediate, mask, black_point, 255, 0, Scalar(), Scalar(), FLOODFILL_MASK_ONLY);

    vector<Point> locations, non_zero_elem;
    Mat mask_roi = mask(Range(1, intermediate.rows - 1), Range(1, intermediate.cols - 1));
    findNonZero(mask_roi, non_zero_elem);
S
Suleyman TURKMEN 已提交
1016
    convexHull(non_zero_elem, locations);
1017
    Point offset = computeOffset(locations);
A
Alexander Nesterov 已提交
1018 1019

    Point temp_remote = locations[0], remote_point;
1020
    const Point delta_diff = offset;
A
Alexander Nesterov 已提交
1021 1022
    for (size_t i = 0; i < locations.size(); i++)
    {
1023
        if (norm(black_point - temp_remote) <= norm(black_point - locations[i]))
A
Alexander Nesterov 已提交
1024 1025 1026
        {
            const uint8_t value = intermediate.at<uint8_t>(temp_remote - delta_diff);
            temp_remote = locations[i];
1027 1028
            if (value == 0) { remote_point = temp_remote - delta_diff; }
            else { remote_point = temp_remote - (delta_diff / 2); }
A
Alexander Nesterov 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        }
    }

    size_t transition_x = 0 , transition_y = 0;

    uint8_t future_pixel = 255;
    const uint8_t *intermediate_row = intermediate.ptr<uint8_t>(remote_point.y);
    for(int i = remote_point.x; i < intermediate.cols; i++)
    {
        if (intermediate_row[i] == future_pixel)
        {
            future_pixel = 255 - future_pixel;
            transition_x++;
        }
    }

    future_pixel = 255;
    for(int j = remote_point.y; j < intermediate.rows; j++)
    {
        const uint8_t value = intermediate.at<uint8_t>(Point(j, remote_point.x));
        if (value == future_pixel)
        {
            future_pixel = 255 - future_pixel;
            transition_y++;
        }
    }

    version = saturate_cast<uint8_t>((std::min(transition_x, transition_y) - 1) * 0.25 - 1);
    if ( !(  0 < version && version <= 40 ) ) { return false; }
    version_size = 21 + (version - 1) * 4;
    return true;
}

bool QRDecode::samplingForVersion()
{
A
Alexander Nesterov 已提交
1064
    CV_TRACE_FUNCTION();
A
Alexander Nesterov 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073
    const double multiplyingFactor = (version < 3)  ? 1 :
                                     (version == 3) ? 1.5 :
                                     version * (5 + version - 4);
    const Size newFactorSize(
                  cvRound(no_border_intermediate.size().width  * multiplyingFactor),
                  cvRound(no_border_intermediate.size().height * multiplyingFactor));
    Mat postIntermediate(newFactorSize, CV_8UC1);
    resize(no_border_intermediate, postIntermediate, newFactorSize, 0, 0, INTER_AREA);

A
Alexander Nesterov 已提交
1074 1075
    const int delta_rows = cvRound((postIntermediate.rows * 1.0) / version_size);
    const int delta_cols = cvRound((postIntermediate.cols * 1.0) / version_size);
A
Alexander Nesterov 已提交
1076

A
Alexander Nesterov 已提交
1077
    vector<double> listFrequencyElem;
A
Alexander Nesterov 已提交
1078
    for (int r = 0; r < postIntermediate.rows; r += delta_rows)
A
Alexander Nesterov 已提交
1079
    {
A
Alexander Nesterov 已提交
1080
        for (int c = 0; c < postIntermediate.cols; c += delta_cols)
A
Alexander Nesterov 已提交
1081 1082
        {
            Mat tile = postIntermediate(
A
Alexander Nesterov 已提交
1083 1084
                           Range(r, min(r + delta_rows, postIntermediate.rows)),
                           Range(c, min(c + delta_cols, postIntermediate.cols)));
A
Alexander Nesterov 已提交
1085
            const double frequencyElem = (countNonZero(tile) * 1.0) / tile.total();
A
Alexander Nesterov 已提交
1086
            listFrequencyElem.push_back(frequencyElem);
A
Alexander Nesterov 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
        }
    }

    double dispersionEFE = std::numeric_limits<double>::max();
    double experimentalFrequencyElem = 0;
    for (double expVal = 0; expVal < 1; expVal+=0.001)
    {
        double testDispersionEFE = 0.0;
        for (size_t i = 0; i < listFrequencyElem.size(); i++)
        {
            testDispersionEFE += (listFrequencyElem[i] - expVal) *
                                 (listFrequencyElem[i] - expVal);
        }
        testDispersionEFE /= (listFrequencyElem.size() - 1);
        if (dispersionEFE > testDispersionEFE)
        {
            dispersionEFE = testDispersionEFE;
            experimentalFrequencyElem = expVal;
        }
    }

    straight = Mat(Size(version_size, version_size), CV_8UC1, Scalar(0));
A
Alexander Nesterov 已提交
1109
    for (int r = 0; r < version_size * version_size; r++)
A
Alexander Nesterov 已提交
1110
    {
A
Alexander Nesterov 已提交
1111 1112 1113
        int i   = r / straight.cols;
        int j   = r % straight.cols;
        straight.ptr<uint8_t>(i)[j] = (listFrequencyElem[r] < experimentalFrequencyElem) ? 0 : 255;
A
Alexander Nesterov 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    }
    return true;
}

bool QRDecode::decodingProcess()
{
#ifdef HAVE_QUIRC
    if (straight.empty()) { return false; }

    quirc_code qr_code;
    memset(&qr_code, 0, sizeof(qr_code));

    qr_code.size = straight.size().width;
    for (int x = 0; x < qr_code.size; x++)
    {
        for (int y = 0; y < qr_code.size; y++)
        {
            int position = y * qr_code.size + x;
            qr_code.cell_bitmap[position >> 3]
A
Alexander Nesterov 已提交
1133
                |= straight.ptr<uint8_t>(y)[x] ? 0 : (1 << (position & 7));
A
Alexander Nesterov 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        }
    }

    quirc_data qr_code_data;
    quirc_decode_error_t errorCode = quirc_decode(&qr_code, &qr_code_data);
    if (errorCode != 0) { return false; }

    for (int i = 0; i < qr_code_data.payload_len; i++)
    {
        result_info += qr_code_data.payload[i];
    }
    return true;
#else
    return false;
#endif

}

bool QRDecode::fullDecodingProcess()
{
#ifdef HAVE_QUIRC
    if (!updatePerspective())  { return false; }
    if (!versionDefinition())  { return false; }
    if (!samplingForVersion()) { return false; }
    if (!decodingProcess())    { return false; }
    return true;
#else
    std::cout << "Library QUIRC is not linked. No decoding is performed. Take it to the OpenCV repository." << std::endl;
    return false;
#endif
}

1166 1167 1168 1169 1170 1171 1172 1173 1174
bool decodeQRCode(InputArray in, InputArray points, std::string &decoded_info, OutputArray straight_qrcode)
{
    QRCodeDetector qrcode;
    decoded_info = qrcode.decode(in, points, straight_qrcode);
    return !decoded_info.empty();
}

cv::String QRCodeDetector::decode(InputArray in, InputArray points,
                                  OutputArray straight_qrcode)
A
Alexander Nesterov 已提交
1175 1176 1177
{
    Mat inarr = in.getMat();
    CV_Assert(!inarr.empty());
1178
    CV_Assert(inarr.depth() == CV_8U);
1179 1180
    if (inarr.cols <= 20 || inarr.rows <= 20)
        return cv::String();  // image data is not enough for providing reliable results
1181 1182 1183 1184 1185 1186 1187 1188

    int incn = inarr.channels();
    if( incn == 3 || incn == 4 )
    {
        Mat gray;
        cvtColor(inarr, gray, COLOR_BGR2GRAY);
        inarr = gray;
    }
A
Alexander Nesterov 已提交
1189 1190 1191 1192

    vector<Point2f> src_points;
    points.copyTo(src_points);
    CV_Assert(src_points.size() == 4);
1193
    CV_CheckGT(contourArea(src_points), 0.0, "Invalid QR code source points");
A
Alexander Nesterov 已提交
1194 1195 1196

    QRDecode qrdec;
    qrdec.init(inarr, src_points);
1197
    bool ok = qrdec.fullDecodingProcess();
A
Alexander Nesterov 已提交
1198

1199
    std::string decoded_info = qrdec.getDecodeInformation();
A
Alexander Nesterov 已提交
1200

1201
    if (ok && straight_qrcode.needed())
A
Alexander Nesterov 已提交
1202 1203 1204 1205 1206 1207
    {
        qrdec.getStraightBarcode().convertTo(straight_qrcode,
                                             straight_qrcode.fixedType() ?
                                             straight_qrcode.type() : CV_32FC2);
    }

1208
    return ok ? decoded_info : std::string();
A
Alexander Nesterov 已提交
1209 1210
}

1211 1212 1213 1214 1215 1216 1217
cv::String QRCodeDetector::detectAndDecode(InputArray in,
                                           OutputArray points_,
                                           OutputArray straight_qrcode)
{
    Mat inarr = in.getMat();
    CV_Assert(!inarr.empty());
    CV_Assert(inarr.depth() == CV_8U);
1218 1219
    if (inarr.cols <= 20 || inarr.rows <= 20)
        return cv::String();  // image data is not enough for providing reliable results
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244

    int incn = inarr.channels();
    if( incn == 3 || incn == 4 )
    {
        Mat gray;
        cvtColor(inarr, gray, COLOR_BGR2GRAY);
        inarr = gray;
    }

    vector<Point2f> points;
    bool ok = detect(inarr, points);
    if( points_.needed() )
    {
        if( ok )
            Mat(points).copyTo(points_);
        else
            points_.release();
    }
    std::string decoded_info;
    if( ok )
        decoded_info = decode(inarr, points, straight_qrcode);
    return decoded_info;
}


N
Nesterov Alexander 已提交
1245
}