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?
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)
You can compute the magnitude like:
dx
and dy
derivatives (using cv::Sobel
)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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With