opencv4学习总结-图像卷积

基础卷积操作

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

using namespace cv;
using namespace std;


int main()
{
    Mat src = imread("E:/opencv_source/opencv_tutorial_data-master/images/home.jpg");
    imshow("src", src);

	int h = src.rows;
	int w = src.cols;
	Mat result = src.clone();
	float filter[3][3] = { 1,1,1,
							1,1,1,
							1,1,1 };
	for (int row = 1; row < h - 1; row++)
	{
		for (int col = 1; col < w - 1; col++)
		{
			//3×3卷积
			int sb = src.at<Vec3b>(row - 1, col - 1)[0]*filter[0][0] + src.at<Vec3b>(row - 1, col)[0] * filter[0][1] + src.at<Vec3b>(row - 1, col + 1)[0] * filter[0][2] +
				src.at<Vec3b>(row, col - 1)[0] * filter[1][0] + src.at<Vec3b>(row, col)[0] * filter[1][1] + src.at<Vec3b>(row, col + 1)[0] * filter[1][2] +
				src.at<Vec3b>(row + 1, col - 1)[0] * filter[2][0] + src.at<Vec3b>(row + 1, col)[0] * filter[2][1] + src.at<Vec3b>(row + 1, col + 1)[0] * filter[2][2];

			int sg = src.at<Vec3b>(row - 1, col - 1)[1] * filter[0][0] + src.at<Vec3b>(row - 1, col)[1] * filter[0][1] + src.at<Vec3b>(row - 1, col + 1)[1] * filter[0][2] +
				src.at<Vec3b>(row, col - 1)[1] * filter[1][0] + src.at<Vec3b>(row, col)[1] * filter[1][1] + src.at<Vec3b>(row, col + 1)[1] * filter[1][2] +
				src.at<Vec3b>(row + 1, col - 1)[1] * filter[2][0] + src.at<Vec3b>(row + 1, col)[1] * filter[2][1] + src.at<Vec3b>(row + 1, col + 1)[1] * filter[2][2];

			int sr = src.at<Vec3b>(row - 1, col - 1)[2] * filter[0][0] + src.at<Vec3b>(row - 1, col)[2] * filter[0][1] + src.at<Vec3b>(row - 1, col + 1)[2] * filter[0][2] +
				src.at<Vec3b>(row, col - 1)[2] * filter[1][0] + src.at<Vec3b>(row, col)[2] * filter[1][1] + src.at<Vec3b>(row, col + 1)[2] * filter[1][2] +
				src.at<Vec3b>(row + 1, col - 1)[2] * filter[2][0] + src.at<Vec3b>(row + 1, col)[2] * filter[2][1] + src.at<Vec3b>(row + 1, col + 1)[2] * filter[2][2];
			result.at<Vec3b>(row, col)[0] = sb / 9;
			result.at<Vec3b>(row, col)[1] = sg / 9;
			result.at<Vec3b>(row, col)[2] = sr / 9;

		}
	}
	imshow("conv-demo", result);
	
    



    waitKey(0);
    destroyAllWindows();

    return 0;
}

卷积核都是1的情况:可以看到图变模糊了,也就是均值滤波

卷积核都是-1的情况:可以看到图跟取反效果是一样的

均值滤波

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

using namespace cv;
using namespace std;


int main()
{
    Mat src = imread("E:/opencv_source/opencv_tutorial_data-master/images/home.jpg");
    imshow("src", src);

    Mat dst;
    blur(src, dst, Size(10, 10), Point(-1, -1), BORDER_DEFAULT);
    imshow("dst", dst);
	
    



    waitKey(0);
    destroyAllWindows();

    return 0;
}

边缘填充

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

using namespace cv;
using namespace std;


int main()
{
    Mat src = imread("E:/opencv_source/opencv_tutorial_data-master/images/home.jpg");
    imshow("src", src);

    int border = 50;
    Mat border_m;
    copyMakeBorder(src, border_m, border, border, border, border, BORDER_DEFAULT);
    imshow("border", border_m);

    waitKey(0);
    destroyAllWindows();

    return 0;
}