lundi 23 février 2015

Rust + Rust Image - Private 'Associated Type'?

The goal is simple - get the colour at (0, 0) and remove any pixels in the image that are similar to it within the specified threshold (16384 in this case). However, the code below doesn't compile:



#![feature(env, old_path, core, old_io)]

extern crate image;

use std::env;
use std::num::ToPrimitive;
use std::old_io::File;
use image::color::FromColor;

use image::Pixel;

fn get_arguments() -> Vec<String> {
let mut argv: Vec<String> = env::args().collect();
argv.remove(0);
return argv;
}

fn remove_background<T:image::GenericImage>(img: &mut T) {
let background_color = img.get_pixel(0, 0).to_rgba();

let transparent_pixel = image::Rgba([0, 0, 0, 0]);

if background_color[3].to_uint().unwrap() > 0 {
for (x, y, color) in img.pixels() {

let rgba = color.to_rgba();

let (dr,dg,db) = (rgba[0] - background_color[0],
rgba[1] - background_color[1],
rgba[2] - background_color[2]);

if (dr*dr + dg*dg + db*db).to_uint().unwrap() < 16384 { img.put_pixel(x, y, transparent_pixel); } // Remove the background colour.

}
}
}

fn main() {
for filepath in get_arguments() {
let img = image::open( &Path::new(filepath) ).unwrap();

remove_background( &mut img );


let ref mut fout = File::create(&Path::new("output.png")).unwrap();
img.save(fout, image::PNG);
}
}


It gives the following error:



src/main.rs:32:83: 32:100 error: mismatched types:
expected `<T as image::image::GenericImage>::Pixel`,
found `image::color::Rgba<_>`
(expected associated type,
found struct `image::color::Rgba`) [E0308]
src/main.rs:32 if (dr*dr + dg*dg + db*db).to_uint().unwrap() < 16384 { img.put_pixel(x, y, transparent_pixel); } // Remove the background colour.


This is presumably because the GenericImage struct defines its own internal "Pixel", which I don't think I can access, but is exactly the same as the normal Pixel struct. How would I get code with this functionality to compile? Every other use of put_pixel I've seen has used get_pixel on the image object and manipulated that, but I need to use a transparent pixel, so that won't work.


Aucun commentaire:

Enregistrer un commentaire