分形不工作的盒子计数功能

问题描述 投票:0回答:1

我正在制作一个 python 程序来拍摄图像并确定具有不同网格大小的分形维数以进行盒子计数。我以前有过它的工作,但它被删除了,我不记得我是如何拥有它的,但我现在有类似的东西。我现在遇到的主要问题是当函数 count_boxes 运行时,每个尺寸的盒子 N=1。

这是我当前的代码 `从 PIL 导入图像 将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt 导入 urllib.request

urllib.request.urlretrieve('https://i.ibb.co/7jC2Qzw/Map-of-GB.png',
   'GB.png')

img = Image.open('GB.png')

img= img.resize((800, 800))
img.save('GB.png')
#img.show()


img_grayscale=img.convert('L') #convert image to greyscale 



img_matrix = np.asmatrix(img_grayscale).copy()  # copy the greyscale values into np matri
Lx=img_grayscale.size[0]
Ly=img_grayscale.size[1]


    thresh = 128  # 0 is black 255 is white
    for i in range (img.size[1]):
    for j in range(img.size[0]):
        if img_matrix[i,j] > thresh:
            img_matrix[i,j] = 255    # white
        else:
            img_matrix[i,j] = 0   # black

img = Image.fromarray(img_matrix)       # save the binarized image


def count_boxes(image, box_size):
    N=0
    step=box_size
    for i in range(0, Lx, step):
       for j in range(0, Ly, step):
           if (img_matrix[i:step,j:step] == 0).any(): 
               N += 1
               return N
       
size=np.arange(800,0,-100)
N=0
Ns=[]
for bs in size:
    N=count_boxes(img,bs)
    Ns.append(N)`

我以前丢失的有效代码给了我 Ns=1 尺寸 800,Ns=4 尺寸 400,Ns=7 尺寸 300,Ns=10 尺寸 200,Ns=27 尺寸 100

现在它只给出 1 作为 Ns 的值。 我该如何解决这个问题?

python python-3.x numpy matplotlib fractals
1个回答
0
投票

要让它恢复到您记录的值,您只需要进行一些小的调整。

  1. 在您的

    count_boxes
    功能中,您需要将切片从
    i:step
    j:step
    ->更改为
    i:i+step
    j:j+step

  2. 你每次都在第一次迭代中从同一个函数返回,所以你需要减少 return 语句,这样它直到循环完成后才会发生。

函数看起来像这样:


def count_boxes(image, box_size):
    N=0
    step=box_size
    for i in range(0, Lx, step):
       for j in range(0, Ly, step):
           if (img_matrix[i:i+step,j:j+step] == 0).any():
               N += 1
    return N

补充说明:

  • 你有一些缩进错误,我假设这些错误只是来自复制和粘贴格式错误。

  • 你在

    img
    行创建了
    img = Image.fromarray(...)
    对象,然后将它传递给
    count_boxes
    函数,但之后从不对它做任何事情,所以它是无用的。

  • 你应该看看 opencv

    cv2
    的阈值和灰度特性。

© www.soinside.com 2019 - 2024. All rights reserved.