想要首先找到焦距,然后使用opencv android实时检测到人脸的距离

2022-09-04 04:49:31

焦距的公式如下:

F = (P x D) / W

但是我无法找到实时出现在检测到的人脸上的矩形的像素值(P):

想要在图像中找到在手机周围绘制的矩形的宽度:

enter image description here

它是使用Python和OpenCV完成的,但我对如何在Java OpenCV中实现它感到困惑。

http://www.pyimagesearch.com/2015/01/19/find-distance-camera-objectmarker-using-python-opencv/


答案 1

在您添加的图像中,您在手机周围绘制了一个正方形,因此您已经拥有正方形的宽度。我从你的问题中了解到,你想在手机周围得到真正的矩形。

为了实现这一点,可以有几个解决方案,但通过处理轮廓来完成的一个解决方案类似于以下代码:

// localImage would be the cropped image of the square you have drawn,
// the global image is the original image and phoneSquare is the Rect you 
// have drawn
localImage = new Mat(globalImage, phoneSqure).clone();

// make the phone black and surroundings white
Imgproc.threshold(localImage, localImage, 127, 255, Imgproc.THRESH_OTSU + Imgproc.THRESH_BINARY_INV);

// get contours
ArrayList<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(canny, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_NONE);

// sort contours by size and get the biggest which is assumed to be the outer contour of the phone
contours.sort(new Comparator<MatOfPoint>() {
                                 @Override
                                 public int compare(MatOfPoint o1, MatOfPoint o2) {
                                     return (int) Math.signum(o2.size().area() - o1.size().area());
                                 }
                             });
MatOfPoints biggestContour = contours.get(contours.size() - 1);
// get the bounding rectangle of the phone, the you can get the width
Rect whatYouWant = Imgproc.boundingRect(biggestContour);

答案 2

推荐