本文是对OpenCV2.4.13文档的部分翻译,作个人学习之用,并不完整。
之前我们学习了如何使用卷积来操作图像,自然有一个问题:如何处理边界,如果某个点在图像的边缘,如何卷积它?
大多数的OpenCV函数采取复制给定图像到另一稍大的图像中来自动填充边界(之前的方法就是这样做的),这样的话,卷积就可以在每一给定的像素周围执行。
在这里,我们简要地探索两种为图像定义额外边界的方法:
BORDER_CONSTANT:用常量填充图像,如黑色(0)
BORDER_REPLICATE:每个边缘的行或列复制到额外的边界中
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/// Global Variables
Mat src, dst;
int top, bottom, left, right;
int borderType;
const char* window_name = "copyMakeBorder Demo";
RNG rng(12345);//随机数生成器,用于生成边界颜色
/**
* @function main
*/
int main()
{
int c;
/// 加载图像
src = imread("fruits.jpg");
if( !src.data )
{
printf(" No data entered, please enter the path to an image file \n");
return -1;
}
/// Brief how-to for this program
printf( "\n \t copyMakeBorder Demo: \n" );
printf( "\t -------------------- \n" );
printf( " ** Press 'c' to set the border to a random constant value \n");
printf( " ** Press 'r' to set the border to be replicated \n");
printf( " ** Press 'ESC' to exit the program \n");
/// 创建窗口
namedWindow( window_name, WINDOW_AUTOSIZE );
/// 为滤波器初始化参数
//初始化定义边界大小的参数:上、下、左、右,这里设为原图像的5%
top = (int) (0.05*src.rows); bottom = (int) (0.05*src.rows);
left = (int) (0.05*src.cols); right = (int) (0.05*src.cols);
dst = src;
imshow( window_name, dst );
for(;;)
{
c = waitKey(500);//每0.5秒颜色随机更新
if( (char)c == 27 )//ESC退出
{ break; }
else if( (char)c == 'c' )//c常量填充
{ borderType = BORDER_CONSTANT; }
else if( (char)c == 'r' )//r边界复制
{ borderType = BORDER_REPLICATE; }
//每0.5秒更新向量,每个随机值在[0,255]
Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
//执行边界填充:原图像、目标图像、上下左右大小、边界类型、值(如果边界类型是常量,就用该值填充)
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
imshow( window_name, dst );
}
return 0;
}
结果: