Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the gradients of image using Python

I wonder how to use Python to compute the gradients of the image. The gradients include x and y direction. I want to get an x gradient map of the image and a y gradient map of the image. Can anyone tell me how to do this?

Thanks~

like image 839
Ariel Avatar asked Apr 09 '18 12:04

Ariel


2 Answers

you can use opencv to compute x and y gradients as below:

import numpy as np
import cv2

img = cv2.imread('Desert.jpg')

kernely = np.array([[1,1,1],[0,0,0],[-1,-1,-1]])
kernelx = np.array([[1,0,-1],[1,0,-1],[1,0,-1]])
edges_x = cv2.filter2D(img,cv2.CV_8U,kernelx)
edges_y = cv2.filter2D(img,cv2.CV_8U,kernely)

cv2.imshow('Gradients_X',edges_x)
cv2.imshow('Gradients_Y',edges_y)
cv2.waitKey(0)
like image 170
user8190410 Avatar answered Oct 18 '22 04:10

user8190410


I think you mean this:

import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt

# Create a black image
img=np.zeros((640,480))
# ... and make a white rectangle in it
img[100:-100,80:-80]=1

# See how it looks
plt.imshow(img,cmap=plt.cm.gray)
plt.show()

enter image description here

# Rotate it for extra fun
img=ndimage.rotate(img,25,mode='constant')
# Have another look
plt.imshow(img,cmap=plt.cm.gray)
plt.show()

enter image description here

# Get x-gradient in "sx"
sx = ndimage.sobel(img,axis=0,mode='constant')
# Get y-gradient in "sy"
sy = ndimage.sobel(img,axis=1,mode='constant')
# Get square root of sum of squares
sobel=np.hypot(sx,sy)

# Hopefully see some edges
plt.imshow(sobel,cmap=plt.cm.gray)
plt.show()

enter image description here


Or you can define the x and y gradient convolution kernels yourself and call the convolve() function:

# Create a black image
img=np.zeros((640,480))
# ... and make a white rectangle in it
img[100:-100,80:-80]=1

# Define kernel for x differences
kx = np.array([[1,0,-1],[2,0,-2],[1,0,-1]])
# Define kernel for y differences
ky = np.array([[1,2,1] ,[0,0,0], [-1,-2,-1]])
# Perform x convolution
x=ndimage.convolve(img,kx)
# Perform y convolution
y=ndimage.convolve(img,ky)
sobel=np.hypot(x,y)
plt.imshow(sobel,cmap=plt.cm.gray)
plt.show()
like image 14
Mark Setchell Avatar answered Oct 18 '22 04:10

Mark Setchell