拉普拉斯算子(Laplacian)可应用到图像边缘检测中。在OpenCV中当kernel大小为3*3时,支持两种kernel算子,分别为:
在OpenCV中默认的计算方式如下,假设有一个5*5的小图像,原始值依次为1,2,…25,如下图红色部分,首先将5*5映射到(5+3-1)*(5+3-1)大小,然后和3*3的kernel做累积和,因为计算结果有可能超出有效值[0, 255]范围,因此在最终还需要判断使其在有效范围内,即小于0为0,大于255为255:
如坐标为(0,0)的计算过程为:12 = 7*0+6*1+7*0+2*1+1*(-4)+2*1+7*0+6*1+7*0.
以下code分别采用两种方式实现,一种是从OpenCV中提取的code(Laplacian_函数),一种是按照上面说明的方式实现的(Laplacian函数),两种方式实现的结果完全一致,但第二种方式更容易理解:
laplacian.cpp:#include "funset.hpp"
#include
#include
#include
#include
#include
#include "common.hpp"
namespace {
typedef struct Rect {
int x, y, width, height;
} Rect;
typedef struct Size {
int width, height;
} Size;
typedef struct Point {
int x, y;
} Point;
int borderInterpolate(int p, int len)
{
if ((unsigned)p
;
} else {
if (len == 1) return 0;
int delta = 1;
do {
if (p
else p = len - 1 - (p - len) - delta;
} while ((unsigned)p >= (unsigned)len);
}
return p;
}
inline unsigned char saturate_cast(float v)
{
int iv = (int)(v + (v >= 0 ? 0.5f : -0.5f));
return (unsigned char)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0);
}
void filter2D(const unsigned char** src, unsigned char* dst, int dststep, int count, int width, int ksize)
{
std::vector coords;
std::vector coeffs;
if (ksize =