简体   繁体   English

如何使用 Python 计算图像的梯度

[英]How to compute the gradients of image using Python

I wonder how to use Python to compute the gradients of the image.我想知道如何使用 Python 来计算图像的梯度。 The gradients include x and y direction.梯度包括 x 和 y 方向。 I want to get an x gradient map of the image and ay gradient map of the image.我想获得图像的 x 梯度图和图像的 a 梯度图。 Can anyone tell me how to do this?谁能告诉我如何做到这一点?

Thanks~谢谢~

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

在此处输入图片说明

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

在此处输入图片说明

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

在此处输入图片说明


Or you can define the x and y gradient convolution kernels yourself and call the convolve() function:或者你可以自己定义 x 和 y 梯度卷积核并调用convolve()函数:

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

you can use opencv to compute x and y gradients as below:您可以使用 opencv 计算 x 和 y 梯度,如下所示:

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)

We can do it with scikit-image filters module functions too, as shown below:我们也可以使用scikit-image filters模块功能来实现,如下所示:

import matplotlib.pylab as plt
from skimage.io import imread
from skimage.color import rgb2gray
from skimage import filters
im = rgb2gray(imread('../images/cameraman.jpg')) # RGB image to gray scale
plt.gray()
plt.figure(figsize=(20,20))
plt.subplot(221)
plt.imshow(im)
plt.title('original', size=20)
plt.subplot(222)
edges_y = filters.sobel_h(im) 
plt.imshow(edges_y)
plt.title('sobel_x', size=20)
plt.subplot(223)
edges_x = filters.sobel_v(im)
plt.imshow(edges_x)
plt.title('sobel_y', size=20)
plt.subplot(224)
edges = filters.sobel(im)
plt.imshow(edges)
plt.title('sobel', size=20)
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM