Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

imgradient matlab equivalent in Python

I am searching for an imgradient MATLAB equivalent in Python. I am aware of cv2.Sobel() and cv2.Laplacian() but it doesn't work as imgradient works in MATLAB. If I could get source code of imgradient.m function that would also be a great help.

Also, I know cv2.Scharr() can also be used but I am not sure what values should I put in parameter to get results equivalent to imgradient in MATLAB?

like image 788
Laveena Avatar asked Dec 15 '17 15:12

Laveena


1 Answers

Because of copyright, we are not allowed to post any code from any of the toolboxes that you'd have to get a license for in MATLAB. Instead what I can do is provide the code that performs the equivalent operations. imgradient simply returns the magnitude and angle of the edge map. All you need to do is apply cv2.Sobel in the x and y directions separately, then calculate the magnitude and angle yourself. You can do this using the standard formulae:

magnitude = sqrt(Gx.^2 + Gy.^2);
angle = atan2(Gy, Gx);

Gx and Gy are the derivatives in the x and y direction respectively, or the output of cv2.Sobel for each direction. Take note that atan2 will give you angles in radians. MATLAB reports the angle in degrees so you'd have to additionally multiply by 180 / pi.

Suppose your image is stored in img. You'd then run cv2.Sobel twice on this image, ensuring that with each invocation, you specify the direction of the derivative you want to find. After that, you calculate the magnitude and angle yourself. Therefore:

import cv2
import numpy as np

img = cv2.imread('....') # Read in the image
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0) # Find x and y gradients
sobely = cv2.Sobel(img,cv2.CV_64F,0,1)

# Find magnitude and angle
magnitude = np.sqrt(sobelx**2.0 + sobely**2.0)
angle = np.arctan2(sobely, sobelx) * (180 / np.pi)
like image 150
rayryeng Avatar answered Oct 24 '22 21:10

rayryeng