1.边缘问题
图像卷积的时候边界像素,不能被卷积操作,原因在于边界像素没有完全跟kernel重叠,所以当3x3滤波时候有1个像素的边缘没有被处理,5x5滤波的时候有2个像素的边缘没有被处理。
2.处理方法
在卷积开始之前增加边缘像素,填充的像素值为0或者RGB黑色,比如3x3在四周各填充1个像素的边缘,这样就确保图像的边缘被处理,在卷积处理之后再去掉这些边缘。openCV中默认的处理方法是: BORDER_DEFAULT,此外常用的还有如下几种:
- BORDER_CONSTANT – 填充边缘用指定像素值
- BORDER_REPLICATE – 填充边缘像素用已知的边缘像素值
- BORDER_WRAP – 用另外一边的像素来补偿填充
3.给图像添加边缘API
void copyMakeBorder( const Mat& src, Mat& dst,int top, int bottom, int left, int right,int borderType, const Scalar& value=Scalar() );
参数1:输入图像
参数2:输出图像
参数3,4,5,6:图像上下左右的边缘长度,一般取值一样
参数7:边缘处理类型
参数8:填充色
4.实现代码
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
char inputName[] = "input name";
char outputName[] = "output name";
int main()
{
Mat src, dst;
src = imread("D:/demo.jpg");
if (src.empty())
{
cout << "找不到图像" << endl;
return -1;
}
namedWindow(inputName, CV_WINDOW_AUTOSIZE);
imshow(inputName, src);
namedWindow(outputName, CV_WINDOW_AUTOSIZE);
//边缘添加
int top = (int)(0.05*src.rows);
int bottom = (int)(0.05*src.rows);
int left = (int)(0.05*src.cols);
int right= (int)(0.05*src.cols);
RNG rng(12345);//生成随机数
int borderType = BORDER_DEFAULT;
int c = 0;
while (true)
{
c = waitKey(500);
if ((char)c == 27)//ESC键
{
break;
}
else if ((char)c=='r')
{
borderType = BORDER_REPLICATE;
}
else if((char)c=='w')
{
borderType = BORDER_WRAP;
}
else if ((char)c =='c')
{
borderType = BORDER_CONSTANT;
}
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//随机生成颜色
copyMakeBorder(src, dst, top, bottom, left, right, borderType, color);
imshow(outputName, dst);
}
waitKey(0);
return 0;
}
通过键盘控制不同边缘处理方法。