Skip to main content
 首页 » 编程设计

python之计算n维图像熵Python

2024年10月01日9exmyth

我正在尝试计算更高维“图像”的熵。显而易见的方法:

from scipy.stats import entropy 
 
kernel_radius=2 
entropy_stack = np.zeros(Stack.shape) 
for ii in range(kernel_radius,entropy_stack.shape[0]-kernel_radius): 
    for jj in range(kernel_radius,entropy_stack.shape[1]-kernel_radius): 
        for kk in range(kernel_radius,entropy_stack.shape[2]-kernel_radius):     
            entropy_stack[ii,jj,kk]=entropy(Stack[ii-kernel_radius:ii+kernel_radius,jj-kernel_radius:jj+kernel_radius,kk-kernel_radius:kk+kernel_radius].flatten()) 

有效,但速度非常慢。

在高维图像中计算熵有什么实现技巧吗?更好的是:是否有任何包具有此功能的优化版本?

我知道 scikit-image 的 entropy 做得很好,但仅限于 2D。同样,我知道 matlab 的 entropyfilt,它的执行速度比我当前的实现快几百倍。

请您参考如下方法:

不幸的是,这是一个同样缓慢的解决方案(尽管代码更清晰并且正确处理了边界)。它使用 scipy.ndimage 中的 generic_filter:

import numpy as np 
from scipy.ndimage import generic_filter 
from scipy.stats import entropy 
 
def _entropy(values): 
    probabilities = np.bincount(values.astype(np.int)) / float(len(values)) 
    return entropy(probabilities) 
 
def local_entropy(img, kernel_radius=2): 
    """ 
    Compute the local entropy for each pixel in an image or image stack using the neighbourhood specified by the kernel. 
 
    Arguments: 
    ---------- 
    img           -- 2D or 3D uint8 array with dimensions MxN or TxMxN, respectively. 
                     Input image. 
    kernel_radius -- int 
                     Neighbourhood over which to compute the local entropy. 
 
    Returns: 
    -------- 
    h -- 2D or 3D uint8 array with dimensions MxN or TxMxN, respectively. 
         Local entropy. 
 
    """ 
    return generic_filter(img.astype(np.float), _entropy, size=2*kernel_radius)