#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char** argv)
{
Mat im = imread("10.jpg", 0);
Mat cont = ~im;
imwrite("1.jpg", cont);
Mat smoothed = Mat(im.rows, im.cols, CV_8UC1, Scalar(0));
// contour smoothing parameters for gaussian filter
threshold(cont, cont, 128, 255, THRESH_BINARY);
imwrite("3.jpg", cont);
// 查找轮廓
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(cont, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
int filterRadius = 3;
int filterSize = 2 * filterRadius + 1;
double sigma = 10;
for (size_t j = 0; j < contours.size(); j++)
{
size_t len = contours[j].size() + 2 * filterRadius;
size_t idx = (contours[j].size() - filterRadius);
vector<float> x, y;
for (size_t i = 0; i < len; i++)
{
x.push_back(contours[j][(idx + i) % contours[j].size()].x);
y.push_back(contours[j][(idx + i) % contours[j].size()].y);
}
// filter 1-D signals
vector<float> xFilt, yFilt;
GaussianBlur(x, xFilt, Size(filterSize, filterSize), sigma, sigma);
GaussianBlur(y, yFilt, Size(filterSize, filterSize), sigma, sigma);
// build smoothed contour
vector<vector<Point> > smoothContours;
vector<Point> smooth;
for (size_t i = filterRadius; i < contours[j].size() + filterRadius; i++)
{
smooth.push_back(Point(xFilt[i], yFilt[i]));
}
smoothContours.push_back(smooth);
Scalar color;
if (hierarchy[j][3] < 0)
{
color = Scalar(255);
}
else
{
color = Scalar(0);
}
drawContours(smoothed, smoothContours, 0, color, -1);
}
imwrite("10.jpg", smoothed);
return 0;
}
C++ 【OpenCV】图像去锯齿
最新推荐文章于 2024-07-17 10:45:42 发布