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

二值化

形态学操作

最终的轮廓

相关推荐
D_evil__38 分钟前
【Effective Modern C++】第三章 转向现代C++:16. 让const成员函数线程安全
c++
Niuguangshuo1 小时前
深入解析Stable Diffusion基石——潜在扩散模型(LDMs)
人工智能·计算机视觉·stable diffusion
迈火1 小时前
SD - Latent - Interposer:解锁Stable Diffusion潜在空间的创意工具
人工智能·gpt·计算机视觉·stable diffusion·aigc·语音识别·midjourney
wfeqhfxz25887821 小时前
YOLO13-C3k2-GhostDynamicConv烟雾检测算法实现与优化
人工智能·算法·计算机视觉
芝士爱知识a2 小时前
2026年AI面试软件推荐
人工智能·面试·职场和发展·大模型·ai教育·考公·智蛙面试
Li emily2 小时前
解决港股实时行情数据 API 接入难题
人工智能·python·fastapi
Aaron15882 小时前
基于RFSOC的数字射频存储技术应用分析
c语言·人工智能·驱动开发·算法·fpga开发·硬件工程·信号处理
Queenie_Charlie2 小时前
前缀和的前缀和
数据结构·c++·树状数组
J_Xiong01172 小时前
【Agents篇】04:Agent 的推理能力——思维链与自我反思
人工智能·ai agent·推理
星爷AG I2 小时前
9-26 主动视觉(AGI基础理论)
人工智能·计算机视觉·agi