C++和opencv对二值图实现没有闭合的图像实现闭合不使用形态学操作代码
以下是使用C++和OpenCV对二值图实现没有闭合的图像实现闭合的代码,不使用形态学操作:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取二值图像
Mat src = imread("binary_image.png", IMREAD_GRAYSCALE);
// 查找轮廓
vector<vector<Point>> contours;
findContours(src, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 遍历每个轮廓
for (int i = 0; i < contours.size(); i++)
{
// 如果轮廓不是封闭的,则进行闭合操作
if (!isContourConvex(contours[i]))
{
vector<Point> hull;
convexHull(contours[i], hull);
drawContours(src, vector<vector<Point>>{hull}, 0, Scalar(255), -1);
}
}
// 显示结果
imshow("Closed Image", src);
waitKey(0);
return 0;
}
代码中,首先读取二值图像,然后使用findContours函数查找轮廓。接下来,遍历每个轮廓,如果轮廓不是封闭的,则使用convexHull函数进行闭合操作。最后,显示结果图像。
需要注意的是,该代码只能处理单个轮廓不闭合的情况。如果图像中有多个轮廓不闭合,需要对每个轮廓进行处理
原文地址: https://www.cveoy.top/t/topic/cuZ8 著作权归作者所有。请勿转载和采集!