在 OpenCV 中测量边缘强度,梯度大小 [英] Measure edge strength in OpenCV, magnitude of gradient

查看:19
本文介绍了在 OpenCV 中测量边缘强度,梯度大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要检查相机焦点的应用程序.为此,我想在单个轴 (1D) 上的几个预定义位置测量边缘强度(梯度大小).图像目标将是在一段时间背景上的黑色对象的简单打印输出.

I have an application where I need to check the focus of a camera. For this, I want to measure edge strength (magnitude of gradient) in several predefined locations on a single axis (1D). The image target will be a simple printout of black objects on a while background.

我在 Python 中使用 OpenCV.我知道 OpenCV 中有几种边缘检测算法,例如 Canny、Sobel、laplace,但所有这些都是为了过滤图像.我想实际测量边缘的强度.OpenCV 中是否有任何算法可以提供此功能?还是我只是编写自己的算法来测量边缘强度?

I am using OpenCV with Python. I know there are several edge detection algorithms within OpenCV like Canny, Sobel, laplace but all of these are to filter the image. I want to actually measure the strength of an edge. Are there any algorithms within OpenCV that can provide this? Or do I just write my own algorithm to measure edge strength?

推荐答案

你可以像这样计算量级:

You can compute the magnitude like:

  1. 计算 dxdy 导数(使用 cv::Sobel)
  2. 计算幅度sqrt(dx^2 + dy^2)(使用cv::magnitude)
  1. Compute dx and dy derivatives (using cv::Sobel)
  2. Compute the magnitude sqrt(dx^2 + dy^2) (using cv::magnitude)

这是一个计算梯度大小的简单 C++ 代码.您可以轻松移植到 Python,因为它只是对 OpenCV 函数的几次调用:

This is a simple C++ code that compute the magnitude of the gradient. You can easily port to Python, since it's just a few calls to OpenCV functions:

#include <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    //Load image
    Mat3b img = imread("path_to_image");

    //Convert to grayscale
    Mat1b gray;
    cvtColor(img, gray, COLOR_BGR2GRAY);

    //Compute dx and dy derivatives
    Mat1f dx, dy;
    Sobel(gray, dx, CV_32F, 1, 0);
    Sobel(gray, dy, CV_32F, 0, 1);

    //Compute gradient
    Mat1f magn;
    magnitude(dx, dy, magn);

    //Show gradient
    imshow("Magnitude", magn);
    waitKey();

    return 0;
}

这篇关于在 OpenCV 中测量边缘强度,梯度大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆