2014-05-12 6 views
2

이미지 A와 같은 이미지가 하나 있는데 이미지 B에 표시되는 주 방향을 감지하고 싶습니다. 코드에서 먼저 가장자리를 감지 한 다음 윤곽을 찾습니다. . 그런 다음 각도를 "각도 = 180 * atan ((2 * m11)/(m20 - m02))/(PI * 2.0) 그러나 결과는 잘못되었습니다! 우리는 이러한 구성 요소의 각도를 볼 수 있습니다 OpenCV를 사용하여 구성 요소의 주 방향 감지

enter image description here

// My function 
Mat edge_Processing(Mat Input_image,int Para_canny_1,int Para_canny_2) 
{ 
Mat edge; 

//blur gray 
blur(Input_image, Input_image, Size(3,3)); 

// Canny edge 
Canny(Input_image,edge, Para_canny_1,Para_canny_2 , 3); 

//imshow("Before contour",edge); 

std::vector<std::vector<cv::Point>> contours; 
cv::findContours(edge, 
    contours, // a vector of contours 
    CV_RETR_EXTERNAL, // retrieve the ezxternal contours 
    CV_CHAIN_APPROX_NONE); // all pixels of each contours 

// Draw black contours on a white image 
cv::Mat result(edge.size(),CV_8U,cv::Scalar(0)); 


std::vector<std::vector<cv::Point>>:: 
    const_iterator itc= contours.begin(); 

//Get the moments 
vector<Moments> mu(contours.size()); 
int moment_count=0; 
while (itc!=contours.end()) 
{ 
    mu[moment_count] = moments(contours[moment_count], false); 

double m11=mu[moment_count].m11; 
double m20=mu[moment_count].m20; 
double m02=mu[moment_count].m02; 

double angle=90; 
    // In case of the situation of dividing by 0   
if (abs(m20 - m02)>0.001) 
{ 
angle = 180*atan((2*m11)/(m20 - m02))/(PI*2.0); 
} 

cout<<angle<<endl; // Here! The angle are wrong! 


++itc; 
moment_count++; 

} 
    // Draw the contour 
cv::drawContours(result,contours, 
    -1, // draw all contours 
    cv::Scalar(255), // in black 
    1); // with a thickness of 1 

//imshow("contour after filtering",result); 

return result; 
}; 

어떤 결과가 여기에 표시됩니다

거의 90있다 그러나 결과는 모두 잘못이다. enter image description here 감사!

답변

3

원하는 작업에 따라 RotatedRect을 사용할 수도 있습니다.

//you got your contour 
RotatedRect minRect = minAreaRect(contour); 
minRect.angle //angle from 0-90 

체크 아웃 this thread, 당신은 그에서 올바른 각도를 계산하는 방법을 볼 수 있습니다.

어쨌든 RotatedRect를 사용하고 윤곽선이 직사각형에 가까운 경우에만 가능합니다.