0

I m going to implement a MatLab code in C++ but there is some problem here is a part of my MatLab code that works perfect, here is my MatLab code :

              connected_comp=bwconncomp(bw_inter);
              centroid=regionprops(connected_comp,'Centroid');

              if size(centroid,1)>1
                 for k=1:size(centroid,1) 
                      centers=abs(centroid(k).Centroid-win_size);
                      if centers(1)<8 && centers(2)<8
                          centroidXY=centroid(k).Centroid;
                      end
                 end
              else
                  centroidXY=centroid(1).Centroid;
              end

And in openCV my code is:

            Mat labelImage(bw_inter.size(), CV_32S);
            int connected_comp = connectedComponents(bw_inter, labelImage, 8);
            Point2f cen1;
            for (int k = 1; k < connected_comp; k++)
            {
                Mat bb = labelImage == k;
                vector<Point> locations;
                cv::findNonZero(bb, locations);
                int nls = (int)locations.size();
                Scalar smean = mean(locations);
                Point2d cen = { smean.val[0], smean.val[1] };
                
                
                if (nls > 1) {

                    for (int kk = 0; kk < nls; kk++)
                    {
                        Point pt = locations[kk];
                        Scalar smean = mean(locations);
                        Point2d cen = { smean.val[0], smean.val[1] };

                        Point2f cens = { abs((float)cen.x - win_size), abs((float)cen.y - win_size) };

                        int x01 = (int)round(cens.x);
                        int y01 = (int)round(cens.y);
                        if (x01 < 7 && y01 < 7) {
                            cen1 = { ((float)cen.x), ((float)cen.y) };
                        }
                    }
                }

                else {
                    
                     cen1 = { abs((float)cen.x ), abs((float)cen.y ) };
                    
                }

They should be the same for me, are they?. OpenCV code doesnt work as perfect as MATLAB. Does anybody have any advice on this?

ishi
  • 11
  • 3
  • 1
    you can use [connectedComponentsWithStats](https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#ga107a78bf7cd25dec05fb4dfc5c9e765f) to begin with, so you already have the centroids. – Miki May 13 '21 at 10:36
  • @Miki, I tried that option too but strangely my points change every time I run and not accurate. – ishi May 14 '21 at 03:42
  • that doesn't make sense. Please provide a [mcve], an input image and the desired result – Miki May 14 '21 at 06:53

0 Answers0