【问题标题】:How to compute the gradients of image using Python如何使用 Python 计算图像的梯度
【发布时间】:2018-04-09 12:13:33
【问题描述】:

我想知道如何使用 Python 来计算图像的梯度。梯度包括 x 和 y 方向。我想获得图像的 x 梯度图和图像的 y 梯度图。谁能告诉我怎么做?

谢谢~

【问题讨论】:

标签: python image image-processing gradient


【解决方案1】:

我认为你的意思是:

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


或者你可以自己定义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()

【讨论】:

  • 对我不起作用,matplotlib 给出错误ValueError: Unsupported dtype
【解决方案2】:

您可以使用 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)

【讨论】:

  • 赞成并感谢您在 OpenCV 上这样做。我正在寻找一个 OpenCV 实现。
【解决方案3】:

我们也可以使用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()

【讨论】:

  • 在你的回答中,渐变被交换了。他们应该是edges_y = filters.sobel_h(im) , edges_x = filters.sobel_v(im)。这是因为 sobel_h 找到水平的,这些边是由 y 方向的导数发现的。可以看到sobel_h操作符使用的kernel是在y方向求导数。
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 2020-09-12
  • 2015-04-27
  • 1970-01-01
  • 2018-04-13
  • 2012-05-12
  • 2013-07-27
  • 1970-01-01
相关资源
最近更新 更多