OpenCV:轮廓及矩形框提取

参考:opencv3/C++轮廓的提取与筛选

#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;
}

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值