我的任务是计算给定图像(分形)的分形维数。具体来说,我想计算信息的维度和相关性的维度(Grassberger,1983 年;Grassberger 和 Procaccia,1983 年)。我无法创建自己的实现,除了 this 之外,我找不到任何实现。我试图将它从 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