python实现sobel,Python中的3D Sobel算法?

该博客讨论了如何在Python中使用ndimage库实现3D Sobel滤波器。作者从2D Sobel滤波开始,通过计算水平和垂直导数并取其范数来获取图像的梯度。然后,扩展到3D情况,需要在三个轴上分别应用Sobel算子。最后,建议使用numpy的`generic_gradient_magnitude`函数直接计算3D矩阵的梯度模长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying to calculate a 3d sobel filter in python. I have a pretty good code for 2d image which is below.

btw. my original image is uint8 type.

preSobel = preSobel.astype('int32')

dx = ndimage.sobel(preSobel, 0) # horizontal derivative

dy = ndimage.sobel(preSobel, 1) # vertical derivative

mag = numpy.hypot(dx, dy) # magnitude

mag *= 255.0 / numpy.max(mag) # normalize (Q&D)

img[i,:,:]=mag

but from my understanding of the wiki page for calculating 2d, i should have multiplied the 1d sobel results rather than hypot :confused

anyway, to go to 3d, I guess I need to calculate 1d sobel on each axis and then multiply all but I'm not sure... Is there any library out there that calculates 3d sobel faster ?

解决方案

First, in reference to your wikipedia link: The multiplication there is referring to the way to construct the sobel convolution kernel, not the end result.

For a 2D sobel filter you need a kernel to get the derivate in x direction, and another kernel to get the derivate in Y direction, e.g.

cad2d0fa7bc5ec59d432e271c35c8cae.png

This is essentially what your two commands do, so if you are using numpy you do not need to construct these kernels yourself.

dx = ndimage.sobel(preSobel, 0) # horizontal derivative

dy = ndimage.sobel(preSobel, 1) # vertical derivative

Now for the 3D case you need 3 operations with 3 kernels, one for dx, dy, dz.

The linked wiki section is telling you how to construct the kernels by multiplying components. The finished sobel kernel for dZ for example is a 3x3x3 matrix that looks like this:

9328aae98bf22d908e26c412b11a6dbf.png

To get the magnitude you still have to take the square root of the squared derivatives (the hypotenuse) afterwards.

I do not have numpy but as far as I can tell from the documentation the ndimage sobel command can deal with any number of dimensions, so again, the kernels are already provided:

dx = ndimage.sobel(your3Dmatrix, 0) # x derivative

dy = ndimage.sobel(your3Dmatrix, 1) # y derivative

dz = ndimage.sobel(your3Dmatrix, 2) # z derivative

now the hypotenuse command probably only take 2 parameters, so you will have to find another way to efficiently calculate mag = sqrt(dxdx + dydy + dz*dz) .

But NumPy should have everything you need for that.

Update

Actually, if you are only interested in the magnitude anyway, there is a complete function in numpy for this:

mag = generic_gradient_magnitude(your3Dmatrix, sobel)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值