gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:48:53 25 4
gpt4 key购买 nike

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

谢谢~

最佳答案

我想你的意思是:

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


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

关于python - 如何使用 Python 计算图像的梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49732726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com