Skip to content

Incorrect upper bound for the number of components in ConnectedComponents algorithms #7607

@sokian

Description

@sokian
System information (version)
  • OpenCV => master
  • Operating System / Platform => OSX 10.12.1
  • Compiler => Apple LLVM version 8.0.0 (clang-800.0.42.1)
Detailed description

New implemented algorithm LablelingGrana has incorrect upper bound for the number of components. And now it's default algorithm for this common case of usage:

cv::connectedComponents(image, labels);

This cause an BAD_ACCESS issue.

Steps to reproduce

Here is an example code that may reproduce an issue.
Here number of components is ROWS * COLS / 3,
But in implementation it's ROWS * COLS / 4.

#include <iostream>
#include <opencv2/imgproc.hpp>

const int ROWS = 1;
const int COLS = 500;
int sum = 0;

void testConnectedComponents() {
 cv::Mat img(cv::Size(COLS, ROWS), CV_8U);
 for (int i = 0; i < COLS * ROWS; i += 3) {
     img.data[i] = 1;
 }
 cv::Mat lab;
 sum += cv::connectedComponents(img, lab);
}

int main() {
 int t = 1000000;
 for (int i = 0; i < t; ++i) {
     testConnectedComponents();
 }
 std::cerr << "Sum: " << sum << std::endl;
 return 0;
}
Solution (Updated)

After @kinchungwong comment, issue changed. Upper bounds for both LabelingGrana and LabelingWu was incorrect.

Correct formulas for both cases are:
4-connectivity: floor((rows * cols + 1) / 2) + 1
8-connectivity: floor((rows + 1) / 2) * floor((cols + 1) / 2) + 1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions