1 | initial version |
In my opinion,the point of the problem is "In facet, there is just one contour in the pictures" and there is my solution,I have erct the two region to show the result,you can get the width or height from the code also
int main( int argc, char** argv )
{
//读入图像,转换为灰度
Mat img = imread("e:/sandbox/1234.png");
Mat bw;
bool dRet;
cvtColor(img, bw, COLOR_BGR2GRAY);
//阈值处理
threshold(bw, bw, 150, 255, CV_THRESH_BINARY);
bitwise_not(bw,bw);
//形态学变化
dilate(bw,bw,Mat(11,11,CV_8UC1));
erode(bw,bw,Mat(11,11,CV_8UC1));
//寻找轮廓
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
/// 计算矩
vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
mu[i] = moments( contours[i], false );
/// 计算中心矩:
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 );
//connect all contours into ONE
for (int i = 0; i < contours.size(); ++i)
{
Scalar color = Scalar( rng12345.uniform(0, 255), rng12345.uniform(0,255), rng12345.uniform(0,255) );
drawContours( img, contours, i, color, 2, 8, hierarchy, 0, Point() );
circle( img, mc[i], 4, color, -1, 8, 0 );
//connect
if (i+1 <contours.size())
line(bw,mc[i],mc[i+1],Scalar(255,255,255));
}
contours.clear();
hierarchy.clear();
//寻找结果
findContours(bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
for (int i = 0;i<contours.size();i++)
{
RotatedRect minRect = minAreaRect( Mat(contours[i]) );
Point2f rect_points[4];
minRect.points( rect_points );
for( int j = 0; j < 4; j++ )
line( img, rect_points[j], rect_points[(j+1)%4],Scalar(255,255,0),2);
float fshort = std::min(minRect.size.width,minRect.size.height); //short
float flong = std::max(minRect.size.width,minRect.size.height); //long
}
imshow("img",img);
waitKey();
return 0;
}