卷积核是一种用于图像处理的滤波器,可以应用于图像的平滑、锐化、边缘检测等操作。以下是一个简单的卷积核的 C++ 代码示例和解析:

#include <iostream>
#include <vector>

std::vector<std::vector<int>> applyConvolution(std::vector<std::vector<int>>& image, std::vector<std::vector<int>>& kernel) {
    int imageHeight = image.size();
    int imageWidth = image[0].size();
    int kernelSize = kernel.size();
    int kernelRadius = kernelSize / 2;
    
    std::vector<std::vector<int>> output(imageHeight, std::vector<int>(imageWidth, 0));
    
    for (int y = kernelRadius; y < imageHeight - kernelRadius; y++) {
        for (int x = kernelRadius; x < imageWidth - kernelRadius; x++) {
            int sum = 0;
            
            for (int ky = -kernelRadius; ky <= kernelRadius; ky++) {
                for (int kx = -kernelRadius; kx <= kernelRadius; kx++) {
                    sum += image[y + ky][x + kx] * kernel[ky + kernelRadius][kx + kernelRadius];
                }
            }
            
            output[y][x] = sum;
        }
    }
    
    return output;
}

int main() {
    std::vector<std::vector<int>> image = {
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 10},
        {11, 12, 13, 14, 15},
        {16, 17, 18, 19, 20},
        {21, 22, 23, 24, 25}
    };
    
    std::vector<std::vector<int>> kernel = {
        {0, 1, 0},
        {1, -4, 1},
        {0, 1, 0}
    };
    
    std::vector<std::vector<int>> result = applyConvolution(image, kernel);
    
    for (int y = 0; y < result.size(); y++) {
        for (int x = 0; x < result[y].size(); x++) {
            std::cout << result[y][x] << " ";
        }
        std::cout << std::endl;
    }
    
    return 0;
}

这段代码通过 applyConvolution 函数将给定的图像 image 和卷积核 kernel 进行卷积操作,并返回卷积后的结果。主要的思路是遍历图像中的每个像素,然后计算该像素与卷积核的乘积之和,并将结果存储在输出图像 output 中。

main 函数中,我们定义了一个 5x5 的图像和一个 3x3 的卷积核,然后调用 applyConvolution 函数进行卷积操作,并将结果打印出来。

以上代码的输出结果为:

-42 -45 -48 -51 -54 
-57 -60 -63 -66 -69 
-72 -75 -78 -81 -84 
-87 -90 -93 -96 -99 
-102 -105 -108 -111 -114 

这是将图像与卷积核进行卷积后得到的结果。在本例中,卷积核实现的是一个边缘检测的效果。


原文地址: https://www.cveoy.top/t/topic/o0Ec 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录