Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure edge strength in OpenCV, magnitude of gradient

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.

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?

like image 485
Chad Avatar asked Nov 12 '15 19:11

Chad


2 Answers

Here's a Python version:

def getGradientMagnitude(im):
    "Get magnitude of gradient for given image"
    ddepth = cv2.CV_32F
    dx = cv2.Sobel(im, ddepth, 1, 0)
    dy = cv2.Sobel(im, ddepth, 0, 1)
    dxabs = cv2.convertScaleAbs(dx)
    dyabs = cv2.convertScaleAbs(dy)
    mag = cv2.addWeighted(dxabs, 0.5, dyabs, 0.5, 0)
    return mag

mag = getGradientMagnitude(im)
like image 99
Brian Burns Avatar answered Oct 19 '22 22:10

Brian Burns


You can compute the magnitude like:

  1. Compute dx and dy derivatives (using cv::Sobel)
  2. Compute the magnitude sqrt(dx^2 + dy^2) (using cv::magnitude)

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;
}
like image 35
Miki Avatar answered Oct 20 '22 00:10

Miki