Ask Your Question
-1

How to sort std::vector<cv::Rect>?

asked 2018-07-29 23:23:45 -0600

Kroll gravatar image

Trying to sort ROI rectangles from left to right.

auto compare = [](const void* p1, const void* p2) -> int
{
    const int* p1x = &(((const cv::Rect*)p1)->width);
    const int* p2x = &(((const cv::Rect*)p2)->width);
    return (*p2x) - (*p1x);
};
qsort(&vec, vec.size(), sizeof(cv::Rect), compare);

But ->width gives the wrong values.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-07-29 23:43:04 -0600

berak gravatar image

your compare function is broken. also please use std::sort, not the c-style qsort.

int compare(const Rect &a, const Rect &b) {
    return a.x - b.x;
}

std::sort(vec.begin(), vec.end(), compare);
edit flag offensive delete link more

Comments

I try this:

auto compare = [](const cv::Rect &a, const cv::Rect &b) -> int
        {
            a.x - b.x;
        };
std::sort(empty_and_right_props.begin(), empty_and_right_props.end(), compare);

But no matters if I change to b.x - a.x it always sort reversed against original no sorted order.

Then after some iterations this function I don't know how falls into an infinite loop.

Kroll gravatar imageKroll ( 2018-07-30 02:15:58 -0600 )edit

your function does not return anything.

please read a book on c++ now !

berak gravatar imageberak ( 2018-07-30 02:49:07 -0600 )edit

Broke my head :) Forgot about return :)

About app crash: now I change the comparator from int to bool and crash is gone.

auto compare = [](const cv::Rect &a, const cv::Rect &b) -> bool
        {
            return a.x > b.x; //left to right
        };
std::sort(empty_and_right_props.begin(), empty_and_right_props.end(), compare);
Kroll gravatar imageKroll ( 2018-07-30 03:12:38 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-07-29 23:23:45 -0600

Seen: 2,166 times

Last updated: Jul 29 '18