Ask Your Question

Finding Largest Contours C++

asked 2017-09-12 20:42:19 -0600

nicksridhar gravatar image

I am currently trying to create a program that finds the edges of a receipt and then crops it accordingly. I used this code to do so:

vector<vector<cv::Point> > contours;
vector<Vec4i> hierarchy;

findContours(edged, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
sort(contours.begin(), contours.end(), compareContourAreas);

vector<cv::Point> target;
for(int i = 0; i < contours.size(); i++){
    vector<cv::Point> c = contours[i];
    double p = arcLength(c, true);
    vector<cv::Point> approx;
    approxPolyDP(c, approx, 0.02*p, true);
    if (approx.size() == 4) {
        target = approx;

This code finds the contours just fine, but doesn't filter them correctly. For example, the following images:

image description image description

The image on the left represents all the contours while the image to the right just represent the target. I'm wondering how I can change my code so that I always receive the edges of the receipt for target.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2017-09-13 01:38:44 -0600

I'm beginning too, but might be worth trying Hough lines: seems a good way to find only long, straight lines (which should be true of most receipt edges).

eg: see this tutorial for Probabilistic Hough Lines at the bottom, then you could calculate the length of each line and find the 4 longest lines.

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2017-09-12 20:42:19 -0600

Seen: 48 times

Last updated: Sep 12