#define _CRT_SECURE_NO_WARNINGS
#include<opencv2/opencv.hpp>
#include<opencv2/xfeatures2d.hpp>
#include<iostream>
using namespace cv;
using namespace xfeatures2d;
using namespace std;
int main()
{
Mat src, dst;
Mat test = imread("data\\7.jpg");
Mat testGray, testBi;
namedWindow("[1]原图");
imshow("[1]原图", test);
if (!test.data)
{
printf("读取错误!\n");
return false;
}
cvtColor(test, testGray, CV_BGR2GRAY);
namedWindow("[2]灰度化");
imshow("[2]灰度化", testGray);
threshold(testGray, testBi, 70, 255, CV_THRESH_BINARY); //可修改阈值
namedWindow("[3]二值化");
imshow("[3]二值化", testBi);
//膨胀
Mat testSwell;
int g_nStructElementSize = 1; //结构元素(内核矩阵)的尺寸
Mat element = getStructuringElement(MORPH_RECT, Size(2 * g_nStructElementSize + 1, 2 * g_nStructElementSize + 1), Point(g_nStructElementSize, g_nStructElementSize));
dilate(testBi, testSwell, element);
namedWindow("[5]膨胀");
imshow("[5]膨胀", testSwell);
src = testSwell;
dst = Mat::zeros(src.size(), CV_8UC3);
//Canny(src, src, 20, 80, 3, false);
std::vector<std::vector<Point>> contours;
std::vector<Vec4i> hierarchy;
findContours(src, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
std::vector<Rect> boundRect(contours.size()); //定义外接矩形集合
int x0 = 0, y0 = 0, w0 = 0, h0 = 0, num = 0;
RNG rng(0);
for (int i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
boundRect[i] = boundingRect((Mat)contours[i]); //查找每个轮廓的外接矩形
drawContours(dst, contours, i, color, 2, 8, hierarchy, 0, Point(0, 0)); //绘制轮廓
x0 = boundRect[i].x;
y0 = boundRect[i].y;
w0 = boundRect[i].width;
h0 = boundRect[i].height;
if (w0 > 30 && h0 > 30)//筛选
{
rectangle(dst, Point(x0, y0), Point(x0 + w0, y0 + h0), Scalar(0, 255, 0), 2, 8); //绘制第i个外接矩形
num++;
//抠图
//取出目标所在矩形区域生成新图像
Rect rect(x0, y0, w0, h0);
Mat ROI = test(rect);
char f[20];
sprintf(f, "ob//ob%d.jpg", num);
string str(f);
dilate(ROI, ROI, element);
imwrite(str, ROI);
}
}
namedWindow("output");
imshow("output", dst);
waitKey();
return 0;
}