forked from dai-pch/ImageSudoku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplit.cpp
74 lines (63 loc) · 2.08 KB
/
split.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "stdafx.h"
using namespace cv;
using namespace std;
vector<Mat> splitImage(Mat const SourceImage)
{
//¶þÖµ»¯
Mat binaryImage;
threshold(SourceImage, binaryImage, 191, 255, CV_THRESH_OTSU);
/*//ÏÔʾ¶þÖµ»¯Í¼Ïñ
namedWindow("¶þÖµ»¯Í¼Ïñ");
imshow("¶þÖµ»¯Í¼Ïñ", binaryImage);*/
//¼ì²âÂÖÀª
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binaryImage, contours, hierarchy, RETR_TREE, CHAIN_APPROX_NONE);
//Ñ°ÕÒ¾ØÐÎÍâ¿ò
int index = -1; //hierarchy.at(0)(2);
index = InterestContour(contours, hierarchy, 81);
if (index < 0)
{
throw logic_error("Can't find right contours.");
}
//ÌáÈ¡³ö×ӱ߽ç
vector<Mat> splited(81);
int subimageWidth = SourceImage.cols / 9, subimageHight = SourceImage.rows / 9;
for (index = hierarchy.at(index)(2); index >= 0; index = hierarchy.at(index)(0))
{
Point2d contourCenter = center(contours.at(index));
int number = (int)(contourCenter.x / subimageWidth) + 9 * (int)(contourCenter.y / subimageHight);
Rect region = ContentsRegion(contours, index);
splited.at(number) = SourceImage(region);
}
return splited;
}
//Calculate the center of a set of points.
Point2d center(const vector<Point> SetOfPoint)
{
Point2d centerPoint;
for (vector<Point>::const_iterator it = SetOfPoint.begin(); it != SetOfPoint.end(); it++)
{
centerPoint.x += it->x;
centerPoint.y += it->y;
}
centerPoint.x /= SetOfPoint.size();
centerPoint.y /= SetOfPoint.size();
return centerPoint;
}
Rect ContentsRegion(vector<vector<Point>> const SourceContours, int const Target)
{
vector<Point> const &contents = SourceContours.at(Target);
Point2d centerPosition = center(contents);
double radio = 0;
vector<Point>::const_iterator it = contents.begin();
double radio_ = fmax(fabs(it->x - centerPosition.x), fabs(it->y - centerPosition.y));
radio = radio_;
for (it++; it != contents.end(); it++)
{
radio_ = fmax(fabs(it->x - centerPosition.x), fabs(it->y - centerPosition.y));
radio = fmin(radio_, radio);
}
radio -= 1;
return Rect((int)(centerPosition.x - radio), (int)(centerPosition.y - radio), (2 * (int)radio + 1), (2 * (int)radio + 1));
}