2015-09-02 74 views
0

基本上,我有一個二進制圖像,其中包含一個對象,我應用輪廓和矩功能來查找質心,並在此檢測對象圖片 。 (不規則物體)Opencv 2.4.11 Java:從質心到輪廓邊線的繪製線

現在我想要做的是生成穿過質心到輪廓邊緣的線(以不同角度),並找出哪條線最長。

任何關於此事的幫助將不勝感激。

回答

1

假設線條從質量中心繪製到質量的周邊,而不是使用測試角度,只需使用輪廓點本身並對每組點執行距離計算即可。例如見下文。 (示例代碼是C++和問題,標籤是java的,我會引火燒身一天時間這一點)。

Mat GrayImage; // input grayscale image, set to something 
    Mat ContourImage; 
    Mat DrawImage = Mat::zeros(GrayImage.size(), CV_8UC3); 
    int thresh = 90; 
    // get a threshold image using Canny edge detector 
    Canny(GrayImage, ContourImage, thresh, thresh * 2, 3); 
    vector< vector<Point> > contours; 
    vector<Vec4i> hierarchy; 
    findContours(ContourImage, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);// retrieves external contours, CHANGES THRESHOLD IMAGE 

    vector<Point2f> centerofMass(contours.size()); 
    vector<Moments> mu(contours.size()); 
    // for every contour in the image 
    for (int i = 0; i < contours.size(); i++) 
    { 
     // draw the contour 
     drawContours(DrawImage, contours, i, Scalar(200, 54, 120), 2, 8, hierarchy, 0, Point()); 
     //calculate center of mass 
     mu[i] = moments(contours[i],false); 
     centerofMass[i] = Point2f(mu[i].m10/mu[i].m00, mu[i].m01/mu[i].m00); 

     double biggestDistance = 0; 
     Point2f farthest_Perimeter_Point; 
     // for each point in the current contour 
     for (int j = 0; j < contours[i].size(); j++) 
     { 
      // get a point that makes up the contour 
      Point2f perimeterofMass(contours[i][j].x, contours[i][j].y); 
      //calculate the distance 
      double dist = cv::norm(centerofMass[i] - perimeterofMass); 
      // determine farthest point 
      if (dist > biggestDistance) 
      { 
       biggestDistance = dist; 
       farthest_Perimeter_Point = perimeterofMass; 
      } 
     } 
     // now we have farthest point as farthest_Perimeter_Point for the current contour at [i] 
     //draw the line because why not; 
     line(DrawImage, centerofMass[i], farthest_Perimeter_Point, Scalar(145, 123, 201)); 
    } 
    imshow("grayimage", GrayImage); 
    imshow("thresholdimage", ContourImage); 
    imshow("drawimage", DrawImage); 

另一個假設是該行從大衆的外線一個出發點繪製質量的另一邊與中心相交。首先從外圍的一個點開始,使用起點和中心點在point-intercept form中形成直線方程。其次找到這條線與另一側相交的位置,現在可以計算距離。第三個確定這些線之間的最大距離。

參考文獻:

Related OpenCV question

Related OpenCV example

+0

我猜寫了代碼越來越一半的距離(從中心到輪廓上的一個點),以及不履行因爲所需該對象是不規則的。 你的其他假設正是我需要做的,但是我找不到任何能夠提取分數的函數。 感謝您的意見 – Shaman