I am using an algorithm to measure fractal dimention (https://francescoturci.net/2016/03/31/box-counting-in-numpy/) or box counting method over 3 images:
My adapted code is:
`
#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)
` among the results, I want to register each fractal dimention in a row from my data frame, however, it is registered just the last calculation.
The results I have are:
# Fractal_dim
0 0 0.000000
1 0 0.000000
2 3 2.000385
what I wan is as follows:
# Fractal_dim
0 1 2.000442
1 2 2.000390
2 3 2.000385
Thank you very much in advance.
As matter of fact I couldn´n answer the exact requierment I wanted to solve, however, I when around by, saving the data in txt format, then converting the txt file to csv, while I can use the Pandas(r) environment.
The code was like
#Calculating fractal dimensión over cutted images step instead saving a csv , it saved a txt
#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 #that variable was initialy randomly set up
counter = 1
#Defining a variable to hol da list
Measures = ["Fractal dimension"]
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]) #the fractal dimension is the OPPOSITE of the fitting coefficient
np.savetxt('/content/lienzo_particula_fracdim'+str(counter)+'.txt', list(zip(scales,Ns)))
#Saving the calculated fractal dimension in the variable measures
Measures.append(str(-coeffs[0]))
print(counter)
print(fractal_cicle)
np.savetxt('/content/raw_data_fracdim_measures.txt', Measures, fmt='%s')
#import pandas as pd
#reading the txt file
read_file = pd.read_csv (r'/content/raw_data_fracdim_measures.txt')
#converting to csv
#df_txt2csv = read_file.to_csv (r'/content/raw_data_fracdim_measures.csv', index=None)
read_file.to_csv (r'/content/raw_data_fracdim_measures.csv', index=None)
#saving csv ans xls file
#df_txt2csv.to_csv('raw_data_bis.csv', index=False) ## line -->read_file.to_csv (r'/content/raw_data_fracdim_measures.csv', index=None)<-- already convert and saved the csv file
#io.excel.xls.writer('raw_data.xls', df)
#df_txt2csv.to_excel('raw_data.xls', index=False)
read_file.to_excel('raw_data_fracdim_measures.xls', index=False)
Despite I had a warning because of the xlwt package no longer maintaining, at the moment, the xls file still being saved.