Mat M, rotated
float angle;
Size rect_size;
float ratio;
int lineSize=0;
Mat temp=threImg.clone();
vector <Vec4i> hierarchy;
vector <vector<Point>> conts;
vector <vector<Point>> conNo;
frame=imread("D://img//1.jpg");
cvtColor(frame,grayImg,CV_BGR2GRAY);
adaptiveThreshold(grayImg,threImg,255,ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY_INV,33,47);
imshow("threImg",threImg);
findContours(threImg,conts,hierarchy,CV_RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
Rect rc;
RotatedRect rect;
float rat;
stringstream ss;
for(int i=0;i<conts.size();i++)
{
drawContours(threImg,conts,i,Scalar(255, 255, 255),1,8,hierarchy);
rc=boundingRect(conts.at(i));
rat=(float)rc.width/rc.height;
cout<<rat<<endl;
cout<<conts.at(i).size()<<endl;
if(rat>0.5 && rat <1)
{
rectangle(frame, rc, Scalar(0, 0, 255), 1, 8, 0 );
conNo.push_back(conts.at(i));
}
imshow("frame",frame);
}
for(int i=0;i<conNo.size();i++)
{
drawContours(temp,conNo,i,Scalar(255, 255, 255),1,8);
rect=minAreaRect(conNo.at(i));
angle = rect.angle;
rect_size = rect.size;
if (rect.angle < -45.)
{
angle += 90.0;
swap(rect_size.width, rect_size.height);
}
ss<<i;
M = getRotationMatrix2D(rect.center, angle, 1.0);
warpAffine(temp, rotated, M, threImg.size(), INTER_CUBIC);
getRectSubPix(rotated, rect_size, rect.center, cropped);
imshow(ss.str(),cropped);
ss.str("");
}