图像分形的Information Dimension与Correlation Dimension计算求助
分形图像的信息维数计算问题及代码调试
我需要计算给定分形图像的信息维数(Information Dimension)和关联维数(Correlation Dimension)(参考Grassberger, 1983; Grassberger and Procaccia, 1983)。自己无法实现算法,也没找到合适的现成方案,仅找到一份C++实现,尝试转成Python后结果异常(比如数值错误或维度为负)。以下是我编写的仅用于计算信息维数的代码:
def information_dimension(image, lmax=64, step=2): """ Calculates the information dimension of the given image. Parameters: image (ndarray): 2D array representing the image lmax (int): maximum box size for calculation step (int): factor by which to increase the box size Returns: float: information dimension of the image """ print("Calculating Information Dimension:") # get image dimensions height, width, dummy = np.shape(image) print(f"Selection w: {width}, h: {height}") # calculate new width and height without edge pixels wn = int((width // lmax) * lmax) hn = int((height // lmax) * lmax) print(f"Calculating over w={wn} and h={hn}") # calculate logarithm of total number of pixels loghw = np.log(hn * wn) # initialize variables fractdim = 0 boxes = [] nboxes = [] boxsize = 2 # loop over increasing box sizes while boxsize <= lmax: inf = 0 te = 0 freq = boxsize * boxsize # loop over boxes for k in range(0, hn - boxsize + 1, boxsize): for l in range(0, wn - boxsize + 1, boxsize): # find minimum and maximum pixel values in box box = image[k:k+boxsize, l:l+boxsize] box_min = np.amin(box) box_max = np.amax(box) # calculate number of boxes needed to cover range of pixel values n = (box_max - box_min) // boxsize + 1 te += int(n) # calculate relative frequency of box and add to information sum inf += freq * (np.log(freq / n) - loghw) # calculate information dimension for current box size print(f"(N: {te}) ", end="") inf = inf / (hn * wn) print(f"inf={inf:.6f} for boxsize {boxsize}") boxes.append(np.log(boxsize)) nboxes.append(inf) # increase box size boxsize *= step # calculate slope of regression line to obtain fractal dimension coeffs = np.polyfit(boxes, nboxes, 1) fractdim = coeffs[0] print(f"\nSlope (Fract. Dim) is {fractdim:.6f} with correlation {np.corrcoef(boxes, nboxes)[0, 1]:.6f}") return fractdim
内容的提问来源于stack exchange,提问作者ExhaustedCProgrammer
相关产品推荐
相关产品推荐

