简单opencv 外轮廓检测以加矩形框

#include <iostream>
#include <opencv2\opencv.hpp>
#include<opencv.hpp>
using namespace std;
using namespace cv;
int main() {
	   Mat threshold_output;
	   vector<vector<Point> > contours;
	   vector<Vec4i> hierarchy;
	   Mat src_gray;
	   Mat frame;
	  //自定义形态学元素结构
	   cv::Mat element5(9, 9, CV_8U, cv::Scalar(1));//5*5正方形,8位uchar型,全1结构元素  
	   Scalar color = Scalar(0, 0, 255);
	   cv::Mat closed;
	   Rect rect;
		frame = imread("./lunkuo.jpg");
		imshow("src", frame);
		Mat image = frame.clone();
		cvWaitKey(1000);
		cvtColor(frame, src_gray, COLOR_BGR2GRAY);
		//使用Canny检测边缘  
		Canny(src_gray, threshold_output, 80, 126, (3, 3));
		//高级形态学闭运算函数  
		cv::morphologyEx(threshold_output, closed, cv::MORPH_CLOSE, element5);
		imshow("canny", threshold_output);
		imshow("erode", closed);
		// 寻找外轮廓轮廓  
		findContours(closed, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
		cout << contours.size() << endl;
		for (int i = 0; i < contours.size(); i++)
		{

			for (int j = 0; j < contours[i].size(); j++)
			{
			
				cout << contours[i][j] << endl;
				//遍历轮廓中每个像素点并且赋值颜色
				//frame.at<Vec3b>(contours[i][j].y, contours[i][j].x) = (0, 0, 255);
			}

		}
	    //转换轮廓点到最大外矩形框
		rect = boundingRect(contours[0]);
		rectangle(image,rect,color);
		//加矩形框后的图片
		imshow("rect", image);
		cvWaitKey(0);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值