1. 程式人生 > >基於能量公式的laplacian平滑迭代處理

基於能量公式的laplacian平滑迭代處理

程式碼網址:https://download.csdn.net/download/lykymy/10799376

視訊網址:https://www.bilibili.com/video/av36468064/

laplacian平滑處理

Mat laplacian_smooth(Mat & image, int time)
{
    char energy_name[50] = "laplacian smooth energy";
	//建立grad_x和grad_y 、abs_grad_x和abs_grad_y矩陣
	Mat grad_x; 
	Mat grad_y;
	//建立sobel運算元處理顯示圖片
	Mat sobel_img = Mat::zeros(image.size(), CV_16S);
	int scale = 1;
	int delta = 0;
	int ddepth = CV_16S;
	//求X方向梯度
	Sobel(image, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
	//求Y方向梯度
	Sobel(image, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
	//構建流場
	for (int i = 0; i < image.rows; i++)
	{
		for (int j = 0; j < image.cols; j++)
		{
			if (grad_x.at<ushort>(i, j) != 0)
			{
				sobel_img.at<short>(i, j) = atan(fabs(grad_y.at<ushort>(i, j) / grad_x.at<ushort>(i, j)));
			}
			else
			{
				sobel_img.at<short>(i, j) = 90;
			}
		}
	}
	
	Mat smooth_img;
	for (int k = 0; k < time; k++)
	{
	  Mat laplacian_img = Mat::zeros(sobel_img.size(), CV_16S);
	  //計算利用laplacian運算元進行平滑
	  for (int i = 1; i < sobel_img.rows - 1; i++)
	  {
 		 for (int j = 1; j < sobel_img.cols - 1; j++)
		 {
		 	laplacian_img.at<short>(i, j) = sobel_img.at<short>(i - 1 , j) + sobel_img.at<short>(i + 1, j) + sobel_img.at<short>(i, j + 1) + sobel_img.at<short>(i, j - 1);
	     }
	  }
	 //構造N行1列的結果矩陣Y
	 Mat result_mat = laplacian_img.reshape(0, laplacian_img.rows * laplacian_img.cols);
	 //將Opencv的Mat轉化為Matrix
	 MatrixXf result_matrix(result_mat.rows, result_mat.cols);
	 cv2eigen(result_mat, result_matrix);
	 MatrixXf coefficient = MatrixXf::Identity(laplacian_img.rows * laplacian_img.cols, laplacian_img.rows * laplacian_img.cols);
	 coefficient = coefficient * 4;
	 VectorXf result_vector = coefficient.lu().solve(result_matrix);
	 //構造顯示影象的大小
	 eigen2cv(result_vector, smooth_img);
	 smooth_img = smooth_img.reshape(1, laplacian_img.rows).clone();
	 energy_solve(smooth_img , energy_name, k);
	 smooth_img.convertTo(sobel_img, CV_16S);
	}
	return smooth_img;
}

效果

原始處理圖片