1.目的
使用openCV函数copyMakeBorder设置边界(添加额外的边界)
2.原理
处理卷积边缘:
(1)大多数用到卷积操作的OpenCV函数都是将给定图像拷贝到另一个轻微变大的图像中,然后自动填充图像边界(通过下面示例代码中的各种方式)。这样卷积操作就可以在边界像素安全执行了(填充边界在操作完成后会自动删除)
(2)本文档将会探讨填充图像边界的两种方法:
<1>BORDER_CONSTANT: 使用常数填充边界 (i.e. 黑色或者0) <2>BORDER_REPLICATE: 复制原图中最临近的行或者列。
3.部分代码解释
(1)copyMakeBorder
/*
copyMakeBorder参数解释
src:输入图片
dst:结果图片
top:上边界宽度
bottom:底边界宽度
left:左边界宽度
right:右边界宽度
borderType:边界类型:
BORDER_CONSTANT:利用常数值填充边界
BORDER_REPLICATE:利用近邻像素填充边界
*/
copyMakeBorder(src, dst, top, bottom, left, right, borderType, value);
4.完整代码
(1)CommonInclude.h
#ifndef COMMON_INCLUDE
#define COMMON_INCLUDE
#include<iostream>
using namespace std;
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
#endif
(2)Border.cpp
#include "CommonInclude.h"
int main(int argc, char** argv){
if(argc < 2){
cout << "more parameters are required!!!" << endl;
return(-1);
}
Mat src, dst;
src = imread(argv[1]);
char windowNameOrigin[] = "Origin";
char windowNameBorder[] = "Border";
char c;
int top,bottom;
int left, right;
int borderType;
Scalar value;
RNG rng = RNG(12345);
if(!src.data){
cout << "error to read image!!!" << endl;
return(-1);
}
imshow(windowNameOrigin, src);
top = (int)(0.05*src.rows);
bottom = (int)(0.05*src.rows);
left = (int)(0.05*src.cols);
right = (int)(0.05*src.cols);
c = waitKey(0);
cout << top << endl << bottom << endl << left << endl << right << endl;
while(true){
if(c == 'r'){
borderType = BORDER_CONSTANT;
}else if(c == 'c'){
borderType = BORDER_REPLICATE;
}else{
break;
}
value = Scalar(rng.uniform(0,255), rng.uniform(0,255), rng.uniform(0,255));
cout << value << endl;
/*
copyMakeBorder参数解释
src:输入图片
dst:结果图片
top:上边界宽度
bottom:底边界宽度
left:左边界宽度
right:右边界宽度
borderType:边界类型:
BORDER_CONSTANT:利用常数值填充边界
BORDER_REPLICATE:利用近邻像素填充边界
*/
copyMakeBorder(src, dst, top, bottom, left, right, borderType, value);
imshow(windowNameBorder, dst);
c = waitKey(0);
}
return(0);
}