close

How to compute the gradients of image using Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to compute the gradients of image using Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to compute the gradients of image using Python?

  1. How to compute the gradients of image using Python?

    you can use opencv to compute x and y gradients as below:
    import numpy as np import cv2 img = cv2.imread('Desert.jpg')

  2. compute the gradients of image using Python

    you can use opencv to compute x and y gradients as below:
    import numpy as np import cv2 img = cv2.imread('Desert.jpg')

Method 1

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()

Method 2

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)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read