1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <iostream> #include"opencv2/opencv.hpp" using namespace std; using namespace cv;
int main(){ Mat img = imread("text.png"); imshow("src",img);
Mat elements = getStructuringElement(MORPH_RECT,Size(10,10)); Mat dstImg; erode(img,dstImg,elements); imshow("erode",dstImg);
Mat imgGray,imgBin; cvtColor(dstImg,imgGray,COLOR_BGR2GRAY); imshow("gray",imgGray); threshold(imgGray,imgBin,100,255,THRESH_BINARY_INV); imshow("bin",imgBin);
vector<vector<Point>> contours; vector<Vec4i> hierarchy; findContours(imgBin,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
for(size_t i=0;i<contours.size();i++){ RotatedRect RRect = minAreaRect(contours[i]); if(RRect.size.area() < 100){ continue; } Point2f vertex[4]; RRect.points(vertex); for(int j=0;j<4;j++){ line(img,Point(vertex[j]),Point(vertex[(j+1)%4]),Scalar(0,255,0),2,LINE_8); } double angle = RRect.angle; if(angle < - 45) angle+=90; Mat rot_mat = getRotationMatrix2D(RRect.center,angle,1); Mat rotated; warpAffine(img,rotated,rot_mat,img.size(),INTER_CUBIC); imshow("res",rotated); } printf("%d",contours.size()); imshow("src2",img);
waitKey(0); }
|