opencv C++ 图像任意mask做卷积

opencv C++ 图像任意mask做卷积


欢迎在评论区留下自己的意见呀!

#include<iostream>
#include<opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/***********************************************************************
 * 
 * Name of Function: 
 *		RandomConvolution()
 *
 * Parameter:
 *		src: the image of input
 *		dst: the image of output
 *		mask: the mask used to make Convolution
 *		coefficient: a parameter used to relize normalization
 *		Sx: the number of 0 need to fill in X coordinate
 *		Sy: the number of 0 need to fill in Y coordinate
 *
 * The Value of Return:
 *		void
 *
 * State: this function can make us to make Convolution with any mask 
 *		
***********************************************************************/

// only used to process gray image
void RandomConvolution(Mat &src, Mat &dst, int **mask, int coefficient, int Sx, int Sy);


int main()
{

	cv::Mat src, grayImg, output;
	
	//mask used to make Convolution
	int mask[3][3] = { {1,1,1},{1,1,1},{1,1,1} };
	int *mask_used[3] = { mask[0],mask[1],mask[2] };
	
	//读取图片
	src = imread("D:\\ProjectVs\\NewProject\\NewProject\\image.jpg");

	if (src.empty())
	{
		std::cout << "Failed to open file!!!" << std::endl;
	}

	cvtColor(src, grayImg, COLOR_BGR2GRAY);
	
	// dispaly some information about the image
	std::cout << "The width of src: " << src.cols << std::endl;
	std::cout << "The height of src: " << src.rows << std::endl;
	std::cout << "The depth of src: " << src.depth() << std::endl;
	std::cout << "The channels of src: " << src.channels() << std::endl;
	cv::imshow("Orginal Image", src);

	RandomConvolution(grayImg, output, mask_used, 9, 1, 1);// only used to process gray image															  
	cv::imshow("OUTPUT", output);
	cv::imwrite("result.jpg", output);//save the output

	waitKey(0);
	return 0;

}

void RandomConvolution(Mat &src, Mat &dst, int **mask, int coefficient, int Sx, int Sy)
{
	cv::Mat preImg;

 	//make a mat dst to accept the pixel and gray after making Convolution
	dst = Mat(src.rows, src.cols, CV_8U, Scalar(0, 0, 0));

	//make a nee image which has filled the edges
	copyMakeBorder(src, preImg, Sx, Sx, Sy, Sy, BORDER_DEFAULT);

	for (int i = Sx; i < src.rows + Sx; i++)
	{
		for (int j = Sy; j < src.cols + Sy; j++)
		{
			int val = 0;
			for (int m = i - Sx; m < i + Sx + 1; m++)
			{
				for (int n = j - Sy; n < j + Sy + 1; n++)
				{
					val += preImg.at<uchar>(m, n)*mask[m - i + Sx][n - j + Sy];
				}
			}
			dst.at<uchar>(i - Sx, j - Sy) = val / coefficient;
		}
	}
}

你可能感兴趣的:(C++,opencv,opencv,c++)