Skip to content

Instantly share code, notes, and snippets.

@brycefisher
Created October 6, 2015 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brycefisher/80ab4fe33e2775e05283 to your computer and use it in GitHub Desktop.
Save brycefisher/80ab4fe33e2775e05283 to your computer and use it in GitHub Desktop.
use image::{GenericImage, ImageBuffer};
extern crate image;
pub fn sobel(input: GenericImage) -> Option<ImageBuffer> {
let (width, height) = input.dimensions();
let raw_input = input.grayscale().raw_pixels();
let mut raw_output = vec![0u8; width*height];
let kernel_x = &[
-1, 0, 1,
-2, 0, 2,
-1, 0, 1
];
let kernel_y = &[
-1, -2, -1,
0, 0, 0,
1, 2, 1
];
let pixel_offset = &[
-1 - width, -(width), 1 - width,
-1, 0, 1,
-1 + width, width, 1 + width
];
let max_y: usize = height - 1;
let max_x: usize = width - 1;
for y in 1..max_y {
for x in 1..max_x {
let mut mag_x = 0f8;
let mut mag_y = 0f8;
let center = y * width + x;
let mut k: usize = 0;
for offset in pixel_offset.iter() {
let index = center + offset;
let pixel = raw_pixels[index as usize];
mag_x += data * kernel_x[k];
mag_y += data * kernel_y[k];
}
raw_output[center] = (mag_x*mag_x + mag_y*mag_y).sqrt();
}
}
ImageBuffer::from_raw(width, height, raw_output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment