Last active
April 13, 2022 10:03
-
-
Save ogrew/899aab13594936d0f173d0c8a7dfe36f to your computer and use it in GitHub Desktop.
フラクタル図形の次元を求める(ボックスカウンティング法)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use linreg::{linear_regression, Error}; | |
use num::Float; | |
use std::env; | |
fn fractal_dim(path: String) { | |
let img = image::open(path).unwrap(); | |
let img = img.to_rgb8(); | |
let width: f32 = img.width() as f32; | |
let height: f32 = img.height() as f32; | |
let edge = 50; | |
let mut size: f32 = width / 3.0; | |
let mut sizes: Vec<f32> = Vec::new(); | |
let mut counts: Vec<f32> = Vec::new(); | |
while size > width / 5000.0 { | |
let mut count: f32 = 0.0; | |
let mut flag: bool = false; | |
let mut x: f32 = 0.0; | |
let mut y: f32 = 0.0; | |
while x < width && y < height { | |
let size_u32 = size as u32; | |
for nx in 0..size_u32 { | |
for ny in 0..size_u32 { | |
let px: u32 = (x as u32) + nx; | |
let py: u32 = (y as u32) + ny; | |
if (px < (width as u32)) && (py < (height as u32)) { | |
let pix = img.get_pixel(px, py); | |
if pix[0] < edge && pix[1] < edge && pix[2] < edge { | |
count += 1.0; | |
flag = true; | |
break; | |
} | |
} | |
} | |
if flag { | |
break; | |
} | |
} | |
x += size; | |
if x >= width { | |
x = 0.0; | |
y += size; | |
} | |
} | |
println!("box size : {} -> count : {}", size, count); | |
sizes.push(Float::ln(size) as f32); | |
counts.push(-Float::ln(count) as f32); | |
size = size / 2.0; | |
} | |
let lr: Result<(f32, f32), Error> = linear_regression(&sizes, &counts); | |
let res: (f32, f32) = match lr { | |
Ok(res) => (res.0, res.1), | |
Err(error) => panic!("{}", error), | |
}; | |
println!("slope: {} / intercept : {}", res.0, res.1); | |
} | |
fn main() { | |
let mut args = env::args(); | |
args.next(); | |
let path = match args.next() { | |
None => { | |
println!("arguments error!"); | |
return; | |
} | |
Some(s) => s, | |
}; | |
println!("Image path : {}", path); | |
fractal_dim(path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment