Python图像轮廓演化C++实现: 防止轮廓超出图像边界
Python图像轮廓演化C++实现: 防止轮廓超出图像边界
本文将带你将一段Python图像轮廓演化代码转换为C++, 并重点讲解如何防止轮廓在演化过程中超出图像边界。
**Python代码:**python# avoid the curvature evolve to the outside of the imagedef fmax(x,y): x[x < 0] = 0 y[y < 0] = 0 x[x > img.shape[1]-1] = img.shape[1]-1 y[y > img.shape[0]-1] = img.shape[0]-1 return y.round().astype(int),x.round().astype(int)
for i in range(iterations): fex = Ix[fmax(x,y)] fey = Iy[fmax(x,y)] x = np.dot(p,x + gammafex) y = np.dot(p,y + gammafey)return x,y
**C++实现:**cpp#include
std::pair<cv::Mat, cv::Mat> fmax(cv::Mat& x, cv::Mat& y, cv::Mat& img) { // 使用OpenCV的cv::max和cv::min函数限制轮廓坐标 cv::Mat x_max = cv::max(x, 0); cv::Mat y_max = cv::max(y, 0); cv::Mat x_min = cv::min(x, img.cols - 1); cv::Mat y_min = cv::min(y, img.rows - 1);
return std::make_pair(y_min.clone(), x_min.clone());}
int main() { // 读取图像 cv::Mat img = cv::imread('input_image.jpg'); cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
// 定义初始轮廓 (示例) int numPoints = 60; std::vector<double> t(numPoints); std::vector<double> x_0(numPoints); std::vector<double> y_0(numPoints);
double start = 0.0; double end = 2.0 * M_PI;
for (int i = 0; i < numPoints; i++) { t[i] = start + i * (end - start) / (numPoints - 1); x_0[i] = 100 + 30 * std::sin(t[i]); y_0[i] = 100 + 30 * std::cos(t[i]); }
// 定义参数 (示例) int iterations = 500; double gamma = 100;
// 初始化蛇轮廓 cv::Mat x = cv::Mat(x_0).clone(); cv::Mat y = cv::Mat(y_0).clone();
// 进行迭代 cv::Mat p_inv; // 假设p矩阵已定义,并计算其逆矩阵 cv::invert(p, p_inv); cv::Mat Ix, Iy; cv::Sobel(Ix, Ix, CV_64F, 1, 0); cv::Sobel(Iy, Iy, CV_64F, 0, 1);
for (int i = 0; i < iterations; i++) { cv::Mat x_round, y_round; std::tie(y_round, x_round) = fmax(x, y, img); cv::Mat fex = Ix.at<double>(y_round, x_round); cv::Mat fey = Iy.at<double>(y_round, x_round); x = p_inv * (x + gamma * fex); y = p_inv * (y + gamma * fey); }
// 打印结果 std::cout << 'x: ' << x << std::endl; std::cout << 'y: ' << y << std::endl;
return 0;}
代码解释:
fmax函数: 该函数用于限制轮廓坐标在图像范围内。在C++实现中,我们使用OpenCV的cv::max和cv::min函数来实现相同的功能。2. OpenCV函数: 使用cv::imread,cv::cvtColor,cv::Sobel等OpenCV函数进行图像读取、颜色空间转换和图像梯度计算。3. 轮廓演化: 使用矩阵运算实现轮廓演化过程,并通过fmax函数确保轮廓始终在图像边界内。
注意:
- 你需要将
input_image.jpg替换为你的图像文件路径。* 代码中假设你已经定义了p矩阵,并计算了其逆矩阵p_inv。 * 这只是一个示例代码,你需要根据你的具体需求调整参数和代码逻辑。
希望这篇文章能帮助你理解如何将Python图像轮廓演化代码转换为C++, 并学习如何防止轮廓超出图像边界。
原文地址: https://www.cveoy.top/t/topic/Fs1 著作权归作者所有。请勿转载和采集!