opencv最小外接矩形

在这里插入图片描述

在这里插入图片描述

#include 
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include 
#include 

#include 

using namespace std;
using namespace cv;


//膨胀的size(3,3)
int dilateValue = 1;
//面积、宽高比
double min_area = 200;
double min_width_div_height = 0.08;
double max_width_div_height = 2.0;

int main()
{
	string imgstr("2.png");
	Mat srcImg = imread(imgstr);
	cv::imshow("原图", srcImg);

	Mat greyImg, dilateImg;
	cvtColor(srcImg, dilateImg, CV_BGR2GRAY);
	threshold(dilateImg, dilateImg, 0, 255, CV_THRESH_OTSU);//自适应二值化
	dilateImg = 255 - dilateImg;//颜色反转
	cv::imshow("反向阈值", dilateImg);
	//获取自定义核
	Mat element = getStructuringElement(MORPH_RECT, Size(dilateValue, dilateValue)); //第一个参数MORPH_RECT表示矩形的卷积核,当然还可以选择椭圆形的、交叉型的
	//膨胀操作
	dilate(dilateImg, dilateImg, element);
	cv::imshow("dilateImg", dilateImg);

	Mat dstImg = srcImg.clone();
	Mat drawdstImg = srcImg.clone();
	vector<vector<Point>> contours;
	vector<Vec4i> hierarcy;
	findContours(dilateImg, contours, hierarcy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
	vector<Rect> boundRect(contours.size());  //定义外接矩形集合
	vector<RotatedRect> box(contours.size()); //定义最小外接矩形集合
	Point2f rect[4];

	map<int, Mat> map_; //key 矩形的左上角坐标  
	for (int i = 0; i < contours.size(); i++)
	{
		box[i] = minAreaRect(Mat(contours[i]));  //计算每个轮廓最小外接矩形
		boundRect[i] = boundingRect(Mat(contours[i]));

		box[i].points(rect);  //把最小外接矩形四个端点复制给rect数组

		double areaValue = (double)boundRect[i].width * (double)boundRect[i].height;
		double width_div_height = (double)boundRect[i].width / (double)boundRect[i].height;

		if (areaValue < min_area || min_width_div_height > width_div_height || width_div_height > max_width_div_height)
		{
			continue;
		}
		cout << "面积 = " << areaValue << "    宽高比 = " << width_div_height << endl;

		Mat roi = dstImg(Rect(Point(boundRect[i].x, boundRect[i].y), Point(boundRect[i].x + boundRect[i].width, boundRect[i].y + boundRect[i].height)));
		map_.emplace(boundRect[i].x, roi);

		rectangle(drawdstImg,
			Point(boundRect[i].x, boundRect[i].y),
			Point(boundRect[i].x + boundRect[i].width, boundRect[i].y + boundRect[i].height),
			Scalar(0, 0, 255), 2, 8);
	}
	for (auto node : map_)
	{
		string str(to_string(node.first));
		//cv::imshow(str, node.second);
		//cv::imwrite("C:\\Users\\GuoJawee\\Desktop\\字符\\"+str+".jpg", node.second);
		//cv::waitKey(0);
	}

	cv::imshow("dst", drawdstImg);
	cv::imwrite("res" + imgstr, drawdstImg);

	cv::waitKey(0);

	return 0;
}

你可能感兴趣的:(opencv)