1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-25 13:23:02 +04:00
Files
Rafael Muñoz Salinas cc1ab3e3ac Merge pull request #28773 from rmsalinas:imgproc_find_truco_contours
imgproc: add findTRUContours - lock-free parallel contour extraction #28773

Integrates the TRUCO algorithm (Threaded Raster Unrestricted Contour Ownership, @cite TRUCO2026) as a transparent fast path inside `cv::findContours`. No API change is required: existing code automatically benefits when `mode=RETR_LIST` and no hierarchy output is requested.

### How it works

When `mode=RETR_LIST` and the caller does not request hierarchy, `findContours` delegates to the TRUCO parallel engine instead of Suzuki-Abe. All ContourApproximationModes are supported; approximation is applied in parallel after extraction. In all other cases the original Suzuki-Abe path is used unchanged.

### Key design ideas
- Row-strip domain decomposition parallelised via `cv::parallel_for_`
- Start-point ownership rule + speculative downward tracing eliminate tile stitching and synchronisation primitives (lock-free)
- 8-bit state space instead of the 32-bit integer labeling required by Suzuki-Abe, giving higher SIMD throughput and lower memory-bandwidth pressure
- Paged contour buffer (`TRUCOPagedContour`) avoids heap reallocation on the hot tracing path
- SIMD-accelerated row scanning via `cv::v_uint8` intrinsics
- Thread count controlled globally via `cv::setNumThreads()`, consistent with OpenCV conventions

### Output correctness

Significant effort has gone into ensuring the output is identical to the original `findContours` in every respect: same contour set, same ordering, and same approximation results for all methods. A dedicated test suite (`test_contours_truco.cpp`) verifies exact match against Suzuki-Abe across all four `ContourApproximationModes` and thread counts from 1 to 39, using noise images, circles, nested rectangles, and mixed scenes.

### Performance vs. Suzuki-Abe (from submitted paper)
- single-thread: ~1.8–1.9× faster (8-bit SIMD advantage)
- 20 threads: ~14–20× faster on i7-13700H (6P+8E, 20T)
- 20 threads: ~10–12× faster on Xeon Silver 4510 (12C/24T)

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
2026-05-14 13:55:39 +03:00

219 lines
6.6 KiB
C++

// 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.
#include "perf_precomp.hpp"
namespace opencv_test { namespace {
CV_ENUM(RetrMode, RETR_EXTERNAL, RETR_LIST, RETR_CCOMP, RETR_TREE)
CV_ENUM(ApproxMode, CHAIN_APPROX_NONE, CHAIN_APPROX_SIMPLE, CHAIN_APPROX_TC89_L1, CHAIN_APPROX_TC89_KCOS)
typedef TestBaseWithParam< tuple<Size, RetrMode, ApproxMode, int> > TestFindContours;
PERF_TEST_P(TestFindContours, findContours,
Combine(
Values( szVGA, sz1080p ), // image size
RetrMode::all(), // retrieval mode
ApproxMode::all(), // approximation method
Values( 32, 128 ) // blob count
)
)
{
Size img_size = get<0>(GetParam());
int retr_mode = get<1>(GetParam());
int approx_method = get<2>(GetParam());
int blob_count = get<3>(GetParam());
RNG rng;
Mat img = Mat::zeros(img_size, CV_8UC1);
for(int i = 0; i < blob_count; i++ )
{
Point center;
center.x = (unsigned)rng % (img.cols-2);
center.y = (unsigned)rng % (img.rows-2);
Size axes;
axes.width = ((unsigned)rng % 49 + 2)/2;
axes.height = ((unsigned)rng % 49 + 2)/2;
double angle = (unsigned)rng % 180;
int brightness = (unsigned)rng % 2;
// keep the border clear
ellipse( img(Rect(1,1,img.cols-2,img.rows-2)), Point(center), Size(axes), angle, 0., 360., Scalar(brightness), -1);
}
vector< vector<Point> > contours;
TEST_CYCLE() findContours( img, contours, retr_mode, approx_method );
SANITY_CHECK_NOTHING();
}
typedef TestBaseWithParam< tuple<Size, ApproxMode, int> > TestFindContoursFF;
PERF_TEST_P(TestFindContoursFF, findContours,
Combine(
Values(szVGA, sz1080p), // image size
ApproxMode::all(), // approximation method
Values(32, 128) // blob count
)
)
{
Size img_size = get<0>(GetParam());
int approx_method = get<1>(GetParam());
int blob_count = get<2>(GetParam());
RNG rng;
Mat img = Mat::zeros(img_size, CV_32SC1);
for (int i = 0; i < blob_count; i++)
{
Point center;
center.x = (unsigned)rng % (img.cols - 2);
center.y = (unsigned)rng % (img.rows - 2);
Size axes;
axes.width = ((unsigned)rng % 49 + 2) / 2;
axes.height = ((unsigned)rng % 49 + 2) / 2;
double angle = (unsigned)rng % 180;
int brightness = (unsigned)rng % 2;
// keep the border clear
ellipse(img(Rect(1, 1, img.cols - 2, img.rows - 2)), Point(center), Size(axes), angle, 0., 360., Scalar(brightness), -1);
}
vector< vector<Point> > contours;
TEST_CYCLE() findContours(img, contours, RETR_FLOODFILL, approx_method);
SANITY_CHECK_NOTHING();
}
typedef TestBaseWithParam< tuple<MatDepth, int> > TestBoundingRect;
PERF_TEST_P(TestBoundingRect, BoundingRect,
Combine(
testing::Values(CV_32S, CV_32F), // points type
Values(400, 511, 1000, 10000, 100000) // points count
)
)
{
int ptType = get<0>(GetParam());
int n = get<1>(GetParam());
Mat pts(n, 2, ptType);
declare.in(pts, WARMUP_RNG);
cv::Rect rect;
TEST_CYCLE() rect = boundingRect(pts);
SANITY_CHECK_NOTHING();
}
typedef TestBaseWithParam< tuple<MatDepth, int> > TestMinEnclosingCircle;
PERF_TEST_P(TestMinEnclosingCircle, minEnclosingCircle,
Combine(
testing::Values(CV_32S, CV_32F),
Values(400, 1000, 10000, 100000)
))
{
int ptType = get<0>(GetParam());
int n = get<1>(GetParam());
Mat pts(n, 2, ptType);
declare.in(pts, WARMUP_RNG);
Point2f center;
float radius;
TEST_CYCLE() minEnclosingCircle(pts, center, radius);
SANITY_CHECK_NOTHING();
}
typedef TestBaseWithParam<int> TestMinEnclosingCircleWorstCase;
PERF_TEST_P(TestMinEnclosingCircleWorstCase, minEnclosingCircle_sequential,
Values(400, 1000, 5000, 10000))
{
int n = GetParam();
vector<Point2f> contour;
for(int i = 0; i < n; ++i) {
float angle = (float)(i * 2 * CV_PI / n);
contour.push_back(Point2f(cos(angle) * 100, sin(angle) * 100));
}
Point2f center;
float radius;
TEST_CYCLE() minEnclosingCircle(contour, center, radius);
SANITY_CHECK_NOTHING();
}
// ============================================================
// findTRUContours performance tests
// ============================================================
typedef TestBaseWithParam< tuple<Size, int, int> > TestFindTRUContours;
PERF_TEST_P(TestFindTRUContours, findTRUContours,
Combine(
Values(sz1080p, sz2160p), // image size
Values(128, 512, 2048), // circle count
Values(1, 0) // nthreads: 1=single-thread baseline, 0=all available
)
)
{
Size img_size = get<0>(GetParam());
int num_circles = get<1>(GetParam());
int nthreads = get<2>(GetParam());
RNG rng(12345);
Mat img = Mat::zeros(img_size, CV_8UC1);
for (int i = 0; i < num_circles; ++i)
{
Point center(rng.uniform(50, img_size.width - 50),
rng.uniform(50, img_size.height - 50));
int radius = rng.uniform(10, 200);
circle(img, center, radius, Scalar::all(255), FILLED);
}
Mat binary;
adaptiveThreshold(img, binary, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 11, 0);
vector<vector<Point>> contours;
int prev_nthreads=cv::getNumThreads();
cv::setNumThreads(nthreads);
TEST_CYCLE() findContours(binary, contours, RETR_LIST, CHAIN_APPROX_NONE);
cv::setNumThreads(prev_nthreads);
SANITY_CHECK_NOTHING();
}
// Baseline: same image, findContours(RETR_LIST, CHAIN_APPROX_NONE) for direct comparison
typedef TestBaseWithParam< tuple<Size, int> > TestFindContoursBaseline;
PERF_TEST_P(TestFindContoursBaseline, findContours_baseline_for_TRUCO,
Combine(
Values(sz1080p, sz2160p),
Values(128, 512, 2048)
)
)
{
Size img_size = get<0>(GetParam());
int num_circles = get<1>(GetParam());
RNG rng(12345);
Mat img = Mat::zeros(img_size, CV_8UC1);
for (int i = 0; i < num_circles; ++i)
{
Point center(rng.uniform(50, img_size.width - 50),
rng.uniform(50, img_size.height - 50));
int radius = rng.uniform(10, 200);
circle(img, center, radius, Scalar::all(255), FILLED);
}
Mat binary;
adaptiveThreshold(img, binary, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 11, 0);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
TEST_CYCLE() findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_NONE);
SANITY_CHECK_NOTHING();
}
} } // namespace