• 卷积边界问题
    • 图像卷积的时候边界像素,不能被卷积操作,原因在于边界像素没有完全跟kernel重叠,所以当3x3滤波时候有1个像素的边缘没有被处理,5x5滤波的时候有2个像素的边缘没有被处理。
  • 处理边缘
    • 在卷积开始之前增加边缘像素,填充的像素值为0或者RGB黑色,比如3x3在四周各填充1个像素的边缘,这样就确保图像的边缘被处理,在卷积处理之后再去掉这些边缘。openCV中默认的处理方法是: BORDER_DEFAULT,此外常用的还有如下几种:
    • BORDER_CONSTANT – 填充边缘用指定像素值
    • BORDER_REPLICATE – 填充边缘像素用已知的边缘像素值。
    • BORDER_WRAP – 用另外一边的像素来补偿填充
  • API说明 – 给图像添加边缘API
copyMakeBorder(
 - Mat src, // 输入图像
 - Mat dst, // 添加边缘图像
 - int top, // 边缘长度,一般上下左右都取相同值,
 - int bottom,
 - int left,
 - int right, 
 - int borderType // 边缘类型
 - Scalar value 
)

完整代码:

#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>

using namespace std;
using namespace cv;

#ifndef P17
#define P17 16
#endif

int main() {
    std::string path = "../fei.JPG";
    cv::Mat img = cv::imread(path, 5);

    string str_input = "input image";
    string str_output = "output image";

    if(img.empty())
    {
        std::cout << "open file failed" << std::endl;
        return -1;
    }

#if P17  //边缘处理
    namedWindow("input", WINDOW_AUTOSIZE);
    namedWindow("output", WINDOW_AUTOSIZE);
    imshow("input", img);

    int top = (int)(0.05*img.rows);
    int bottom = (int)(0.05*img.rows);
    int left = (int)(0.05*img.cols);
    int right = (int)(0.05*img.cols);
    int border_type = BORDER_WRAP;

    RNG rng(12345);
    int c = 0;

    Mat dest;
    Scalar color;

    while(true)
    {
        c = waitKey(500);
        if((char)c == 27)
        {
            break;
        }else if((char)c == 'r')
        {
            border_type = BORDER_REFLECT;
        }else if((char)c == 'c')
        {
            border_type = BORDER_CONSTANT;
        }

        color = Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255));
        copyMakeBorder(img, dest,top, bottom,left,right,border_type, color);
        imshow("output",dest);
    }
#endif

    cv::waitKey(0);
    cv::destroyAllWindows();
    return 0;
}

效果图:
【OpenCV图像处理】1.16 处理边缘_卷积

更多文章请关注《万象专栏》