找出这张文档图的方块的矩形

原图如下:

找出这张文档图的方块的矩形_第1张图片

效果图如下:

找出这张文档图的方块的矩形_第2张图片

代码如下:

// a7.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <opencv245.h>
#include <vector>

using namespace std;
using namespace cv;

void paintRect(Mat &src, Rect &rect)
{
	float LTopX = static_cast<float>(rect.x);
	float LTopY = static_cast<float>(rect.y);
	float RBtmX = static_cast<float>(rect.x + rect.width - 1);
	float RBtmY = static_cast<float>(rect.y + rect.height - 1);
	
	Point LTopPonit(LTopX, LTopY);
	Point RBtmPoint(RBtmX, RBtmY);

	rectangle( src, LTopPonit, RBtmPoint, Scalar(0, 0, 255), 1, 8);

	

}


void imgProc(Mat &image, Vector<Rect> &VecRect)
{
	

	for (auto it = VecRect.begin(); it != VecRect.end(); it++)
	{
		
		paintRect(image, *it);
	}


}

int _tmain(int argc, _TCHAR* argv[])
{
	Mat src, dst, element;
	Vector<Rect> rects;
	int count = 0;
	Rect rect;
	RNG rng = theRNG();

	src = imread("C:\\Users\\sony\\Desktop\\pic\\3.jpg",0);
	
	
	threshold(src, dst, 133, 255, THRESH_BINARY);
	element = getStructuringElement(MORPH_RECT, Size(5,5),Point(-1, -1));
	morphologyEx(dst, dst, MORPH_CLOSE, element, Point(-1,-1));
	morphologyEx(dst, dst, MORPH_CLOSE, element, Point(-1,-1));
	dilate(dst,dst,Mat(),Point(-1,-1),1);
	erode(dst,dst,Mat(),Point(-1,-1),1);
	
	
	/*cvtColor(dst,dst,CV_GRAY2BGR);*/
	
	cvtColor(src,src,CV_GRAY2BGR);
	

	for (int j = 0; j < dst.rows; j++)
	{
		for (int i = 0; i < dst.cols; i++)
		{
			if ( dst.at<uchar>(j, i) == 0 )
			{
				
				floodFill(dst, Point(i, j), count + 1, &rect);
				rects.push_back(rect);
				
				count++;
			}		
		}
	}

	imgProc(src, rects);

	resize(src,src,Size(300,300));
	resize(dst,dst,Size(800,800));
	imshow("src", src);
	imshow("dst", dst);
	imwrite("C:\\Users\\sony\\Desktop\\pic\\3b.jpg",src);
	waitKey(0);

	return 0;
}


你可能感兴趣的:(找出这张文档图的方块的矩形)