Measuring the size of object in C++ using OpenCV

asked 2018-03-23 05:05:04 -0600

DS Itachi gravatar image

updated 2018-03-23 05:11:34 -0600

i need help to achieve measuring the size of objects using OpenCV.

I got a Link for this functionality, but it was done in Python.I have tried to convert in C++ but could n't achieve. Honestly i don't know C++ & Python too i was tried below code.I am trying to implement this functionality in iOS app.

    - (void)processImage:(cv::Mat &)image; 
    {
    Mat gray;
    cvtColor(image, gray, CV_BGRA2GRAY);
    cv::GaussianBlur(gray, gray, cvSize(7, 7), 0);
    cv::Canny(gray, gray, 50, 100);
    cv::dilate(gray, gray, NULL);
    cv::erode(gray, gray, NULL);
    cv::findContours(gray, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

//sort the contours from left-to-right and initialize the 'pixels per metric' calibration variable
   sort(contours.begin(), contours.end(), [](const vector<cv::Point>& c1, const
vector<cv::Point>& c2){
       return contourArea(c1, false) < contourArea(c2, false);
   });

 for(int i=0; i<contours.size(); i++)
 {
     if (contourArea(contours[i]) < 100) {
         break;
     }
     std::vector<cv::Point2f> boxPts;
     gray.copyTo(orig);
     box = minAreaRect(contours[i]);
     cv::boxPoints(box, boxPts);
  // here i got freeze 'numpy',np i don't know exactly what's this can't move forward
     // box = np.array(box, dtype="int")   
}
   }

Can someone help me to doing this functionality in C++. If anyone other c++ source/link is available for this functionality kindly share with me.Thanks in advance

edit retag flag offensive close merge delete

Comments

1

what is intended by sorting the contours here ? you sort by size, not position(as stated in the comment), also, the small ones will be the first in the vector, and your area condition will break out at once.

then, please lookup the pinhole camera model.

to measure size, you need to know the distance & the fov, to measure distance, the size & fov.

(or need to have something with known size next to it)

i'd recommend, you go back to the python code, and try to UNDERSTAND it, before doing any further coding.

berak gravatar imageberak ( 2018-03-23 05:13:10 -0600 )edit

Hi @berak thanks for your response i don't exactly the intend of sorting that document say's "These contours are then sorted from left-to-right (allowing us to extract our reference object) ".

DS Itachi gravatar imageDS Itachi ( 2018-03-23 05:17:34 -0600 )edit

well, your c++ code is not doing that. (you could try to get the contour's boundingRect(), and sort byx position of that)

but again, try to understand, what is done, and why, before hastily coding anything

berak gravatar imageberak ( 2018-03-23 05:31:58 -0600 )edit