Chad - 1 year ago 193

Python Question

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?

Answer Source

You can compute the magnitude like:

- Compute
`dx`

and`dy`

derivatives (using`cv::Sobel`

) - 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;
}
```