Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert OpenCV's Rect to dlib's rectangle?

I use OpenCV's face detector with C++ for dlib's face alignment instead of dlib's detector because of slow speed.
To use dlib's face alignment, I have to pass the detection rectangle to the face alignment function.
However, I cannot do that even though dlib's detector is ok.
Because std::vector<rectangle> detsis used in dlib's sample code, I tried to assign as shown below, but I couldn't.
Note that detect_rect is face detection rectangle by OpenCV's detector.

dets[0].l = detect_rect.left;
dets[0].t = detect_rect.top;
dets[0].r = detect_rect.right;
dets[0].b = detect_rect.bottom;

Could you tell me any advice?

Thank you.

like image 907
univ_student Avatar asked Jan 19 '16 08:01

univ_student


2 Answers

It has to be noted that OpenCV uses the following definition:

OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the right and bottom boundaries are not.

dlib's definition includes all boundaries, so the conversion function has to take care of shifting bottom right corner by 1.

Here's a function that I have in my Utils.h

static cv::Rect dlibRectangleToOpenCV(dlib::rectangle r)
{
  return cv::Rect(cv::Point2i(r.left(), r.top()), cv::Point2i(r.right() + 1, r.bottom() + 1));
}

And the other way around:

static dlib::rectangle openCVRectToDlib(cv::Rect r)
{
  return dlib::rectangle((long)r.tl().x, (long)r.tl().y, (long)r.br().x - 1, (long)r.br().y - 1);
}
like image 141
lahjaton_j Avatar answered Sep 20 '22 07:09

lahjaton_j


This answer is for Python.
You can use the construct of dlib rectangle wiz. dlib.rectangle(). You can use the OpenCV's facial bounding boxes
x = face[0] y = face[1] w = face[2] h = face[3]
and map them to dlib.rectangle(x, y, w, h).
Then you can call predictor code shape = predictor(img, rect)

like image 45
Chandra Kanth Avatar answered Sep 17 '22 07:09

Chandra Kanth