OpenCV 闭合轮廓检测

63 篇文章 2 订阅
48 篇文章 11 订阅

 

 

这个好像是骨头什么的,但是要求轮廓闭合,于是对图片进行一下膨胀操作,再次检测轮廓就好了。

 

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

#include "stdafx.h"


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

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

#include "stdafx.h"



#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp> 
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
//#include "highlight"
//#include "highgui.h"


#pragma comment(lib,"opencv_core2410d.lib")        
#pragma comment(lib,"opencv_highgui2410d.lib")        
#pragma comment(lib,"opencv_imgproc2410d.lib")  

#define PI 3.1415926

using namespace std;
using namespace cv;

int main()
{
	// Read input binary image

	char *image_name = "test.bmp";
	cv::Mat image = cv::imread(image_name);
	if (!image.data)
		return 0; 

	


	
	// 从文件中加载原图  
	  // IplImage *pSrcImage = cvLoadImage(image_name, CV_LOAD_IMAGE_UNCHANGED);  
	  Mat gray(image.size(),CV_8U);
		  
	  cvtColor(image,gray,CV_BGR2GRAY); 
		 // 转为2值图
	 threshold(gray,gray,145,255,cv::THRESH_BINARY_INV);
	//cvThreshold(pSrcImage,pSrcImage,145,255,cv::THRESH_BINARY_INV);
		   
	
	   //image = gray;

	   cv::namedWindow("Binary Image");
	   cv::imshow("Binary Image",gray);



	   cv::Mat element(5,5,CV_8U,cv::Scalar(255));

	   cv::dilate(gray,gray,element);
	   //cv::erode(image,image,element);

	   cv::namedWindow("dilate Image");
	   cv::imshow("dilate Image",gray);


	// Get the contours of the connected components
	std::vector<std::vector<cv::Point>> contours;

	cv::findContours(gray, 
		contours, // a vector of contours 
		CV_RETR_EXTERNAL , // retrieve the external contours
		CV_CHAIN_APPROX_NONE); // retrieve all pixels of each contours

	// Print contours' length
	std::cout << "Contours: " << contours.size() << std::endl;
	std::vector<std::vector<cv::Point>>::const_iterator itContours= contours.begin();
	for ( ; itContours!=contours.end(); ++itContours) 
	{

		std::cout << "Size: " << itContours->size() << std::endl;
	}

	// draw black contours on white image
	cv::Mat result(image.size(),CV_8U,cv::Scalar(255));
	cv::drawContours(result,contours,
		-1, // draw all contours
		cv::Scalar(0), // in black
		2); // with a thickness of 2

	cv::namedWindow("Contours");
	cv::imshow("Contours",result);









	// Eliminate too short or too long contours

	/*
	int cmin= 100;  // minimum contour length
	int cmax= 1000; // maximum contour length
	std::vector<std::vector<cv::Point>>::const_iterator itc= contours.begin();
	while (itc!=contours.end()) {

		if (itc->size() < cmin || itc->size() > cmax)
			itc= contours.erase(itc);
		else 
			++itc;
	}
	
	*/

	// draw contours on the original image
	cv::Mat original= cv::imread(image_name);
	cv::drawContours(original,contours,
		-1, // draw all contours
		cv::Scalar(255,255,0), // in white
		2); // with a thickness of 2

	cv::namedWindow("Contours on Animals");
	cv::imshow("Contours on Animals",original);

	

	// Let's now draw black contours on white image
	result.setTo(cv::Scalar(255));
	cv::drawContours(result,contours,
		-1, // draw all contours
		cv::Scalar(0), // in black
		1); // with a thickness of 1
	image= cv::imread("binary.bmp",0);

	// testing the bounding box 
	


	

	std::vector<std::vector<cv::Point>>::const_iterator itc_rec= contours.begin();
	while (itc_rec!=contours.end())
	{
		cv::Rect r0= cv::boundingRect(cv::Mat(*(itc_rec)));
		cv::rectangle(result,r0,cv::Scalar(0),2);
			++itc_rec;
	}

	/*
	// testing the enclosing circle 
	float radius;
	cv::Point2f center;
	cv::minEnclosingCircle(cv::Mat(contours[1]),center,radius);
	cv::circle(result,cv::Point(center),static_cast<int>(radius),cv::Scalar(0),2);

	//	cv::RotatedRect rrect= cv::fitEllipse(cv::Mat(contours[1]));
	//	cv::ellipse(result,rrect,cv::Scalar(0),2);

	// testing the approximate polygon
	std::vector<cv::Point> poly;
	cv::approxPolyDP(cv::Mat(contours[2]),poly,5,true);

	std::cout << "Polygon size: " << poly.size() << std::endl;

	// Iterate over each segment and draw it
	std::vector<cv::Point>::const_iterator itp= poly.begin();
	while (itp!=(poly.end()-1)) {
		cv::line(result,*itp,*(itp+1),cv::Scalar(0),2);
		++itp;
	}
	// last point linked to first point
	cv::line(result,*(poly.begin()),*(poly.end()-1),cv::Scalar(20),2);

	// testing the convex hull
	std::vector<cv::Point> hull;
	cv::convexHull(cv::Mat(contours[3]),hull);

	// Iterate over each segment and draw it
	std::vector<cv::Point>::const_iterator it= hull.begin();
	while (it!=(hull.end()-1)) {
		cv::line(result,*it,*(it+1),cv::Scalar(0),2);
		++it;
	}
	// last point linked to first point
	cv::line(result,*(hull.begin()),*(hull.end()-1),cv::Scalar(20),2);

	// testing the moments

	// iterate over all contours
	itc= contours.begin();
	while (itc!=contours.end()) {

		// compute all moments
		cv::Moments mom= cv::moments(cv::Mat(*itc++));

		// draw mass center
		cv::circle(result,
			// position of mass center converted to integer
			cv::Point(mom.m10/mom.m00,mom.m01/mom.m00),
			2,cv::Scalar(0),2); // draw black dot
	}

	*/

	cv::namedWindow("Some Shape descriptors");
	cv::imshow("Some Shape descriptors",result);


	cv::waitKey();
	return 0;


}


 

实现效果:

 

 

在使用Python和OpenCV进行视频闭合轮廓检测时,你可以按照以下步骤进行操作: 1. 导入必要的库: ```python import cv2 import numpy as np ``` 2. 打开视频文件并创建视频捕获对象: ```python cap = cv2.VideoCapture('video.mp4') ``` 3. 循环读取视频帧并进行处理: ```python while cap.isOpened(): ret, frame = cap.read() if not ret: break # 对帧进行预处理,例如灰度化、高斯模糊等 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) # 进行边缘检测 edges = cv2.Canny(blurred, 50, 150) # 执行轮廓检测 contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 对每个轮廓进行处理 for contour in contours: # 计算轮廓的周长 perimeter = cv2.arcLength(contour, True) # 进行轮廓近似,获取多边形的顶点 epsilon = 0.02 * perimeter approx = cv2.approxPolyDP(contour, epsilon, True) # 判断是否为闭合轮廓(多边形顶点数为4) if len(approx) == 4: # 绘制闭合轮廓 cv2.drawContours(frame, [approx], 0, (0, 255, 0), 2) # 显示处理后的帧 cv2.imshow('Contours', frame) # 按下 'q' 键退出循环 if cv2.waitKey(1) == ord('q'): break ``` 4. 释放视频捕获对象并关闭窗口: ```python cap.release() cv2.destroyAllWindows() ``` 这个代码示例将读取视频文件中的每一帧,将其转换为灰度图像并进行边缘检测。然后,它执行轮廓检测,并对每个轮廓进行近似,判断是否为闭合轮廓(多边形顶点数为4),如果是则绘制该轮廓。最后,它在窗口中显示处理后的帧,按下 'q' 键退出循环。 请注意,这只是一个简单的示例代码,你可能需要根据实际情况进行调整和优化。另外,你需要根据你的实际需求来修改视频文件的路径和其他参数。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值