OpenCvSharp函数:Laplacian边缘检测

Laplacian边缘检测

函数说明

计算图像的拉普拉斯(Laplacian)算子
函数通过相加Sobel算子的x和y的二阶导数计算Laplacian算子:
当kSize>1时,计算如下

dst = Δ src = ∂ 2 src ∂ x 2 + ∂ 2 src ∂ y 2 \texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2} dst=Δsrc=x22src+y22src

当kSize==1时,使用如下3x3的核

[ 0 1 0 1 − 4 1 0 1 0 ] \begin{bmatrix} 0 & 1 & 0 \\ 1 & -4 & 1 \\ 0 & 1 & 0\end{bmatrix} 010141010

函数原型

void Laplacian(InputArray src,
	OutputArray dst,
	MatType ddepth,
	int ksize = 1,
	double scale = 1.0,
	double delta = 0.0,
	BorderTypes borderType = BorderTypes.Reflect101)

参数说明

参数 说明                            
InputArray src 输入图像, 一般为灰度图
OutputArray dst 输出图像。大小与通道数与输入图像一致
MatType ddepth 期望的输出深度,具体见Depth combinations表
int ksize 用于计算二阶导数的核大小,为正奇数
double scale 计算的导数值的可选比例因子,默认为1。
double delta 计算结果上加该值,可理解为调亮(正数)或调暗(负数)
BorderTypes borderType 边框外像素取值方法,不支持Wrap

图像示例

OpenCvSharp函数:Laplacian边缘检测_第1张图片

代码示例

Mat src;
string winName = "Laplacian Demo";


public void Run()
{
    if (!Utils.SelectFile(out string fileName)) fileName = ImagePath.Lena;
    src = Cv2.ImRead(fileName, ImreadModes.Color);
    if (src.Empty()) throw new Exception($"图像打开有误:{fileName}");
    //
    Cv2.GaussianBlur(src, src, new Size(3, 3), 0, 0);

    Cv2.CvtColor(src, src, ColorConversionCodes.BGR2GRAY);

    Cv2.NamedWindow(winName, WindowFlags.AutoSize;
    var tbKSizeName = "kSize 2n+1";
    Cv2.CreateTrackbar(tbKSizeName, winName, 15, KSizeOnChanged);
    Cv2.SetTrackbarPos(tbKSizeName, winName, 1);

    var tbScaleName = "scale n/10";
    Cv2.CreateTrackbar(tbScaleName, winName, 100, SCaleOnChanged);
    Cv2.SetTrackbarPos(tbScaleName, winName, 10);

    var tbDeltaName = "Delta n-50";
    Cv2.CreateTrackbar(tbDeltaName, winName, 100, DeltaOnChanged);
    Cv2.SetTrackbarPos(tbDeltaName, winName, 50);

    bool loop = true;
    while (loop)
    {
        if (Cv2.WaitKey(50) == 27) break;
    }
    Cv2.DestroyAllWindows();
}
private void OnChanged()
{
    using var dst = new Mat();
    Cv2.Laplacian(src, dst, MatType.CV_16S, kSize, scale, delta, BorderTypes.Default);
    // converting back to CV_8U
    Cv2.ConvertScaleAbs(dst, dst);
    Utils.PutText(dst, $"kSize={kSize},Scale={scale},Delta={delta}");
    Cv2.ImShow(winName, dst);
}

int kSize = 3;
private void KSizeOnChanged(int pos, IntPtr userData)
{
    kSize = pos * 2 + 1;
    OnChanged();
}

double scale = 1;
private void SCaleOnChanged(int pos, IntPtr userData)
{
    scale = pos / 10.0D;
    OnChanged();
}

double delta = 0;
private void DeltaOnChanged(int pos, IntPtr userData)
{
    delta = pos - 50;
    OnChanged();
}

OpenCvSharp函数示例(目录)
参考
https://docs.opencv.org/4.7.0/d5/db5/tutorial_laplace_operator.html

你可能感兴趣的:(OpenCVSharp学习,OpenCvSharp函数,opencv,c#,图像处理)