简体   繁体   中英

Find center of objects using OpenCV4Android

Sometime ago I wrote a code in python using OpenCV to find the center of objects:

x= np.zeros(4)
y = np.zeros(4)
i = 0
for cnt in contour:
    area = cv2.contourArea(cnt)
    if area>=100 and area<=5000:
        hull = cv2.convexHull(cnt)
        x[i] = hull[:,:,0].mean()
        y[i] = hull[:,:,1].mean()
        i = i + 1

Since OpenCV has Java interface too I want to implement this code in an android app. I wrote a somewhat similar code but I am not getting what I want. mopOut is just giving some random things which I don't need:

for(int i=0; i< contours.size();i++) {
        if (Imgproc.contourArea(contours.get(i)) > 1000 && Imgproc.contourArea(contours.get(i)) < 10000 ) {
            Imgproc.convexHull(contours.get(i),hull);
            MatOfPoint mopOut = new MatOfPoint();
            mopOut.create((int)hull.size().height,1, CvType.CV_32SC2);
            for(int j = 0; j < hull.size().height ; j++)
            {
                int index = (int)hull.get(j, 0)[0];
                double[] point = new double[] {
                        contours.get(i).get(index, 0)[0], contours.get(i).get(index, 0)[1]
                };
                mopOut.put(i, 0, point);
            }
        }
    }

Can someone tell me the right way to do it? Or else any other better alternative way to find the centers?

I am new to Java and Android app development, so I might be missing something simple. Thanks for help!

So finally I managed to write a similar code in Java:

int k = 0;
for(int i=0; i< contours.size();i++) {
   if (Imgproc.contourArea(contours.get(i)) > 1000 && Imgproc.contourArea(contours.get(i)) < 10000 ) {
       Scalar colour = new Scalar(90,255,255);
       Imgproc.drawContours(image,contours,i,colour,-1);
       Imgproc.convexHull(contours.get(i),hull);
       List<Point> l = new ArrayList<Point>();
       l.clear();
       double sum_x = 0;
       double sum_y = 0;
       int j;
       for (j = 0; j < hull.size().height; j++) {
           l.add(contours.get(i).toList().get(hull.toList().get(j)));
           sum_x += l.get(j).x;
           sum_y += l.get(j).y;
       }
       x[0][k] = sum_x / j;
       x[1][k] = sum_y / j;
       k++;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM