You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图像盒计数法分形维度计算结果无法正确保存至CSV文件

盒计数法计算分形维度的数据保存问题

我使用基于Numpy的盒计数法对3张图像计算分形维度,3张图像如下:

  • 第一张图像:First image
  • 第二张图像:Second image
  • 第三张图像:Third image

改写后的代码如下:

#importing pandas (library needed)
import pandas as pd
import openpyxl
import io
import numpy as np
import pylab as pl
 
def rgb2gray(rgb):
    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray
randshapes = 3
counter = 1
for fractal_cicle in range(randshapes):
  
  path = "/content/lienzo_particula_cutted"+str(counter)+".png"
  image=rgb2gray(pl.imread(path))
  
  # finding all the non-zero pixels
  pixels=[]
  for i in range(image.shape[0]):
    for j in range(image.shape[1]):
      if image[i,j]>0:
        pixels.append((i,j))
  
  Lx=image.shape[1]
  Ly=image.shape[0]
  print (Lx, Ly)
  pixels=pl.array(pixels)
  print (pixels.shape)
  
  #computing the fractal dimension
  #considering only scales in a logarithmic list
  scales=np.logspace(0.01, 1, num=10, endpoint=False, base=2)
  Ns=[]
  
  # looping over several scales
  for scale in scales:
    print ("======= Scale :",scale)
    # computing the histogram
    H, edges=np.histogramdd(pixels, bins=(np.arange(0,Lx,scale),np.arange(0,Ly,scale)))
    Ns.append(np.sum(H>0))
  
  # linear fit, polynomial of degree 1
  coeffs=np.polyfit(np.log(scales), np.log(Ns), 1)
  
  pl.plot(np.log(scales),np.log(Ns), 'o', mfc='none')
  pl.plot(np.log(scales), np.polyval(coeffs,np.log(scales)))
  pl.xlabel('log $\epsilon$')
  pl.ylabel('log N')
  pl.savefig('Coeff graph'+str(counter)+'.pdf')

  print ("The Hausdorff dimension is", -coeffs[0]) 
  np.savetxt('/content/lienzo_particula_fracdim'+str(counter)+'.txt', list(zip(scales,Ns)))
  
  
  #creating a dictionary
  raw_data = {'#': [], 'Fractal_dim': []}
  
  #creating the data frame
  df = pd.DataFrame(raw_data, columns = ['#', 'Fractal_dim'])
  
  print(counter)
  print(fractal_cicle)
  df.loc[fractal_cicle,'#'] = counter
  df.loc[fractal_cicle,'Fractal_dim'] = -coeffs[0]
  #print(df)
  counter += 1
print(df)
df.to_csv('raw_data.csv', index=False)
#io.excel.xls.writer('raw_data.xls', df)
df.to_excel('raw_data.xls', index=False)

问题描述

目前代码仅能将最后一次计算的分形维度结果保存至CSV/Excel文件,前两次结果未正确写入。

当前输出结果:

#  Fractal_dim
0  0     0.000000
1  0     0.000000
2  3     2.000385

期望输出结果:

#  Fractal_dim
0  1     2.000442
1  2     2.000390
2  3     2.000385

解决方案

问题出在循环内部每次都重新初始化raw_data字典和df数据框,导致每次循环都会覆盖之前的结果,最终只保留最后一次循环的数据。

修改后的代码:

#importing pandas (library needed)
import pandas as pd
import openpyxl
import io
import numpy as np
import pylab as pl
 
def rgb2gray(rgb):
    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray

randshapes = 3
counter = 1
# 提前创建空的数据框
raw_data = {'#': [], 'Fractal_dim': []}
df = pd.DataFrame(raw_data, columns=['#', 'Fractal_dim'])

for fractal_cicle in range(randshapes):
  
  path = "/content/lienzo_particula_cutted"+str(counter)+".png"
  image=rgb2gray(pl.imread(path))
  
  # finding all the non-zero pixels
  pixels=[]
  for i in range(image.shape[0]):
    for j in range(image.shape[1]):
      if image[i,j]>0:
        pixels.append((i,j))
  
  Lx=image.shape[1]
  Ly=image.shape[0]
  print (Lx, Ly)
  pixels=pl.array(pixels)
  print (pixels.shape)
  
  #computing the fractal dimension
  #considering only scales in a logarithmic list
  scales=np.logspace(0.01, 1, num=10, endpoint=False, base=2)
  Ns=[]
  
  # looping over several scales
  for scale in scales:
    print ("======= Scale :",scale)
    # computing the histogram
    H, edges=np.histogramdd(pixels, bins=(np.arange(0,Lx,scale),np.arange(0,Ly,scale)))
    Ns.append(np.sum(H>0))
  
  # linear fit, polynomial of degree 1
  coeffs=np.polyfit(np.log(scales), np.log(Ns), 1)
  
  pl.plot(np.log(scales),np.log(Ns), 'o', mfc='none')
  pl.plot(np.log(scales), np.polyval(coeffs,np.log(scales)))
  pl.xlabel('log $\epsilon$')
  pl.ylabel('log N')
  pl.savefig('Coeff graph'+str(counter)+'.pdf')

  print ("The Hausdorff dimension is", -coeffs[0]) 
  np.savetxt('/content/lienzo_particula_fracdim'+str(counter)+'.txt', list(zip(scales,Ns)))
  
  # 将当前结果写入数据框对应行
  df.loc[fractal_cicle] = [counter, -coeffs[0]]
  
  counter += 1

print(df)
df.to_csv('raw_data.csv', index=False)
df.to_excel('raw_data.xls', index=False)

修改说明

  • 将raw_data和df的初始化移到循环外部,避免每次循环重置数据框
  • 每次循环用df.loc[fractal_cicle] = [counter, -coeffs[0]]直接赋值当前行,确保所有计算结果都被正确保存
  • 循环结束后,数据框会包含3次计算的完整结果,导出的文件即可得到期望输出

内容的提问来源于stack exchange,提问作者Daniel Molina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:50:36