C++ opencv-3.4.1 提取不规则物体的轮廓

在学习opencv的时候,对一张照片,需要标注照片上物体的不规则轮廓。

如图:

使用opencv进行物体的轮廓处理,关键在于对照片的理解,前期的照片处理的越好最后调用api出来的结果就越接近理想值。

提取照片中物体分如下三步:

  1. 图像去噪,高斯模糊
  2. 二值化
  3. 去除噪点,形态学操作,去除较小的噪点
  4. 进行轮廓查找
cpp 复制代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace cv;
using namespace std;
Mat src, dst, gray_src;
char input_image[] = "input image";
char output_image[] = "output image";

int main(int argc, char ** argv) {

	src = imread("d:/src.jpg");
	if (src.empty()) {
		printf("colud not load image ..\n");
		return -1;
	}

	//namedWindow(input_image, WINDOW_AUTOSIZE);
	//namedWindow(output_image, WINDOW_AUTOSIZE);
	imshow("input_image", src);

	// 均值降噪
	Mat blurImg;
	GaussianBlur(src, blurImg, Size(15, 15), 0, 0);
	imshow("GaussianBlur image", blurImg);

	// 二值化
	Mat binary;
	cvtColor(blurImg, gray_src, COLOR_BGR2GRAY);
	threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
	imshow("binary", binary);

	// 闭操作进行联通物体内部
	Mat morphImage;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
	morphologyEx(binary, morphImage, MORPH_CLOSE, kernel, Point(-1, -1), 10);
	imshow("morphology", morphImage);

	// 获取最大轮廓
	vector<vector<Point>> contours;
	vector<Vec4i> hireachy;
	findContours(morphImage, contours, hireachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
	Mat connImage = Mat::zeros(src.size(), CV_8UC3);
	for (size_t t = 0; t < contours.size(); t++) {
		Rect rect = boundingRect(contours[t]);
		if (rect.width < src.cols / 2) continue;
		if (rect.width > src.cols - 20) continue;

		double area = contourArea(contours[t]);
		double len = arcLength(contours[t], true);


		drawContours(connImage, contours, t, Scalar(0, 0, 255), 1, 8, hireachy);
		printf("area of star could : %f \n", area);
		printf("lenght of star could : %f \n", len);
	}
	imshow("output_image", connImage);



	waitKey(0);
	return 0;
}

二值化

形态学操作

最终的轮廓

相关推荐
johnny2336 分钟前
强化学习RL
人工智能
乌恩大侠11 分钟前
无线网络规划与优化方式的根本性变革
人工智能·usrp
放羊郎13 分钟前
基于萤火虫+Gmapping、分层+A*优化的导航方案
人工智能·slam·建图·激光slam
王哈哈^_^20 分钟前
【数据集+完整源码】水稻病害数据集,yolov8水稻病害检测数据集 6715 张,目标检测水稻识别算法实战训推教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
SEOETC38 分钟前
数字人技术:虚实交融的未来图景正在展开
人工智能
boonya1 小时前
从阿里云大模型服务平台百炼看AI应用集成与实践
人工智能·阿里云·云计算
amhjdx1 小时前
三维技术 + AI 动画,焕活古镇科技人文新表达,天南文化助力 2025 年世界互联网大会乌镇峰会
人工智能·科技
鹿子沐1 小时前
LLamaFactory模型导出量化
人工智能·语言模型
skywalk81631 小时前
尝试Auto-coder.chat使用星河社区AIStudio部署的几个大模型:文心4.5-21b、Deepseek r1 70b、llama 3.1 8b
linux·服务器·人工智能·大模型·aistudio
鹿子沐1 小时前
LlamaFactory微调效果与vllm部署效果不一致
人工智能·llama