将OpenCV的Rect转换为dlib的矩形?

10

我使用C++中的OpenCV人脸检测器来代替dlib的检测器进行人脸对齐,因为dlib的检测器速度较慢。
要使用dlib的人脸对齐功能,我必须将检测到的矩形传递给人脸对齐函数。
然而,即使dlib的检测器正常工作,我也无法做到这一点。
因为dlib的示例代码中使用了std::vector<rectangle> dets,我尝试按照下面所示的方式进行赋值,但是失败了。
请注意,detect_rect是由OpenCV检测器检测到的人脸矩形。

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

你能给我一些建议吗?

谢谢。


dlib使用.l .t .r .b,您能解释一下它们的含义吗?也许是从图像边界到某些距离(因此是某种裁剪)?如果是这样,您将不得不使用:.l = rect.x; .t = rect.y; .r = imageWidth - (rect.x+rect.width); .b = imageHeight - (rect.y+rect.height); - Micka
1
Dlibs的人脸检测器不慢。您确定是在发布模式下运行吗? - TruckerCat
抱歉,我已经自己解决了!下面的代码可以工作!rectangle rect(left, top, right, bottom);``dets.push_back(rect);谢谢! - univ_student
4个回答

23

需要注意的是,OpenCV使用以下定义:

通常,OpenCV假定矩形的顶部和左侧边界包括,而右侧和底部边界不包括

dlib的定义包括所有边界,因此转换函数必须注意将右下角向下移动1个单位。

这是我在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));
}

反之亦然:

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);
}

谢谢您的建议。我已经自己解决了!下面的代码是有效的!rectangle rect(left, top, right, bottom); dets.push_back(rect); 我认为我的代码和您的代码是一样的。感谢您的回答! - univ_student

7

这个想法是正确的,但是你在访问cv::Rect元素时做错了。

应该是:

dets[0].l = detect_rect.x;
dets[0].t = detect_rect.y;
dets[0].r = detect_rect.x + detect_rect.width;
dets[0].b = detect_rect.y + detect_rect.height;

谢谢您的建议。我已经自己解决了!下面的代码可以工作!rectangle rect(left, top, right, bottom);``dets.push_back(rect);谢谢! - univ_student

2
这篇回答是关于Python的。你可以使用dlib矩形构造函数dlib.rectangle()。你可以使用OpenCV的人脸边界框:
x = face[0] y = face[1] w = face[2] h = face[3]
并将它们映射到dlib.rectangle(x, y, w, h)。然后,你可以调用预测器代码shape = predictor(img, rect)

0

将OpenCV矩形坐标转换为Python中的DLIB矩形坐标:

如果检测结果是从OpenCV获取的矩形坐标列表:

left = detections[0]
top = detections[1]
right = detections[2]
bottom = detections[3] 
dlibRect = dlib.rectangle(left, top, right, bottom) 

dlibRect 将会是 dlib 类型的矩形。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接