Skip to content

Commit a3590df

Browse files
kornelskiandrews05
authored andcommitted
Optimize co-occurence matrix
1 parent 36de543 commit a3590df

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/reduction/palette.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -201,14 +201,18 @@ fn most_popular_edge_color(num_colors: usize, png: &PngImage) -> usize {
201201
}
202202

203203
// Calculate co-occurences matrix
204-
fn co_occurrence_matrix(num_colors: usize, png: &PngImage) -> Vec<Vec<usize>> {
205-
let mut matrix = vec![vec![0; num_colors]; num_colors];
204+
fn co_occurrence_matrix(num_colors: usize, png: &PngImage) -> Vec<Vec<u32>> {
205+
let mut matrix = vec![vec![0u32; num_colors]; num_colors];
206206
let mut prev: Option<ScanLine> = None;
207+
let mut prev_val = None;
207208
for line in png.scan_lines(false) {
208209
for i in 0..line.data.len() {
209210
let val = line.data[i] as usize;
210-
if i > 0 {
211-
matrix[line.data[i - 1] as usize][val] += 1;
211+
if val > num_colors {
212+
continue;
213+
}
214+
if let Some(prev_val) = prev_val.replace(val) {
215+
matrix[prev_val][val] += 1;
212216
}
213217
if let Some(prev) = &prev {
214218
matrix[prev.data[i] as usize][val] += 1;
@@ -220,7 +224,7 @@ fn co_occurrence_matrix(num_colors: usize, png: &PngImage) -> Vec<Vec<usize>> {
220224
}
221225

222226
// Calculate edge list sorted by weight
223-
fn weighted_edges(matrix: &[Vec<usize>]) -> Vec<(usize, usize)> {
227+
fn weighted_edges(matrix: &[Vec<u32>]) -> Vec<(usize, usize)> {
224228
let mut edges = Vec::new();
225229
for i in 0..matrix.len() {
226230
for j in 0..i {

0 commit comments

Comments
 (0)