raster 0.2.0

Image processing lib for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//!  A module for filtering pixels.


// from rust
use std::cmp;

// from external crate


// from local crate
use error::{RasterError, RasterResult};
use Image;
use Color;

/// An enum for the various modes that can be used for blurring.
#[derive(Debug)]
pub enum BlurMode {
    Box,
    Gaussian
}

/// Apply box or Gaussian blur.
///
/// # Examples
/// ### Box Blur
///
/// ```
/// use raster::{filter, BlurMode};
///
/// // Create image from file
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::blur(&mut image, BlurMode::Box).unwrap();
/// raster::save(&image, "tests/out/test_filter_box_blur.jpg").unwrap();
/// ```
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_box_blur.jpg)
///
/// ### Gaussian Blur
///
/// ```
/// use raster::{filter, BlurMode};
///
/// // Create image from file
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::blur(&mut image, BlurMode::Gaussian).unwrap();
/// raster::save(&image, "tests/out/test_filter_gaussian_blur.jpg").unwrap();
/// ```
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_gaussian_blur.jpg)
///
pub fn blur(mut src: &mut Image, mode: BlurMode) -> RasterResult<()>{
    match mode {
        BlurMode::Box => blur_box(src),
        BlurMode::Gaussian => blur_gaussian(src)
    }
}

/// Apply brightness.
///
/// A brightness of < 0.0 will darken the image and brightness of > 1.0 will lighten it.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::brightness(&mut image, 1.5).unwrap();
/// raster::save(&image, "tests/out/test_filter_brightness.jpg").unwrap();
/// ```
///
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_brightness.jpg)
///
pub fn brightness(mut src: &mut Image, factor: f32) -> RasterResult<()>{
    let w: i32 = src.width;
    let h: i32 = src.height;

    // if gamma < 0.01 || gamma > 9.99{
    //     return Err(format!("Incorrect gamma value {}. Must be in range 0.01 - 9.99.", gamma));
    // }
    // let factor = 255.0 * factor;

    for y in 0..h {
        for x in 0..w {

            let p = try!(src.get_pixel(x, y));
            let r = cmp::max(0, cmp::min(255, (p.r as f32 * factor) as i32));
            let g = cmp::max(0, cmp::min(255, (p.g as f32 * factor) as i32));
            let b = cmp::max(0, cmp::min(255, (p.b as f32 * factor) as i32));
            let a = cmp::max(0, cmp::min(255, (p.a as f32 * factor) as i32)); // TODO: Should alpha be included?

            try!(src.set_pixel(x, y, Color::rgba(r as u8, g as u8, b as u8, a as u8)));

        }
    }

    Ok(())
}

/// Apply a convolution matrix.
///
/// The divisor is applied as the last step of convolution.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// // Create image from file
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// let matrix: [[i32; 3]; 3] = [
///     [0, 0, 0],
///     [0, 1, 0],
///     [0, 0, 0]
/// ];
/// filter::convolve(&mut image, matrix, 1).unwrap();
/// raster::save(&image, "tests/out/test_filter_convolve.jpg").unwrap();
/// ```
pub fn convolve(src: &mut Image, matrix: [[i32; 3]; 3], divisor: i32) -> RasterResult<()> {

    let w: i32 = src.width;
    let h: i32 = src.height;
    let m_size = 3; // Matrix size

    let copy = src.clone(); // Create a copy as input of pixels

    for y in 0..h {
        for x in 0..w {

            let mstarty = y - 1;
            let mstartx = x - 1;

            let mut accum_red: i32 = 0;
            let mut accum_green: i32 = 0;
            let mut accum_blue: i32 = 0;
            let mut accum_alpha: i32 = 0;

            for (m_index_y, mut src_y) in (0..).zip(mstarty..mstarty + m_size) {
                if src_y < 0 {
                    src_y = 0;
                } else if src_y > h - 1 {
                    src_y = h - 1;
                }

                for (m_index_x, mut src_x) in (0..).zip(mstartx..mstartx + m_size) {
                    if src_x < 0 {
                        src_x = 0;
                    } else if src_x > w - 1 {
                        src_x = w - 1;
                    }

                    let pixel = try!(copy.get_pixel(src_x, src_y));
                    accum_red += pixel.r as i32 * matrix[m_index_y][m_index_x];
                    accum_green += pixel.g as i32 * matrix[m_index_y][m_index_x];
                    accum_blue += pixel.b as i32 * matrix[m_index_y][m_index_x];
                    accum_alpha += pixel.a as i32 * matrix[m_index_y][m_index_x];
                }
            }

            if divisor != 1 {
                accum_red /= divisor;
                accum_green /= divisor;
                accum_blue /= divisor;
                accum_alpha /= divisor;
            }

            if accum_red < 0 {
                accum_red = 0;
            }
            if accum_green < 0 {
                accum_green = 0;
            }
            if accum_blue < 0 {
                accum_blue = 0;
            }
            if accum_alpha < 0 {
                accum_alpha = 0;
            }

            if accum_red > 255 {
                accum_red = 255;
            }
            if accum_green > 255 {
                accum_green = 255;
            }
            if accum_blue > 255 {
                accum_blue = 255;
            }
            if accum_alpha > 255 {
                accum_alpha = 255;
            }

            try!(src.set_pixel(x, y, Color::rgba(accum_red as u8, accum_green as u8, accum_blue as u8, accum_alpha as u8)));

        }
    }

    Ok(())
}

/// Apply emboss.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// // Create image from file
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::emboss(&mut image).unwrap();
/// raster::save(&image, "tests/out/test_filter_emboss.jpg").unwrap();
/// ```
///
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_emboss.jpg)
///
pub fn emboss(mut src: &mut Image) -> RasterResult<()>{
    let matrix: [[i32; 3]; 3] = [
        [-2, -1, 0],
        [-1, 1, 1],
        [0, 1, 2]
    ];

    convolve(src, matrix, 1)
}

/// Apply a gamma correction.
///
/// Gamma can be a value from 0.01 - 9.99.
/// A gamma < 1.0 will darken and a gamma > 1.0 will lighten the image.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::gamma(&mut image, 2.0).unwrap();
/// raster::save(&image, "tests/out/test_filter_gamma.jpg").unwrap();
/// ```
///
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_gamma.jpg)
///
// http://stackoverflow.com/questions/14088889/changing-a-color-brightness
pub fn gamma(mut src: &mut Image, gamma: f32) -> RasterResult<()>{
    let w: i32 = src.width;
    let h: i32 = src.height;

    if gamma < 0.01 || gamma > 9.99 {
        return Err(RasterError::InvalidGamma(gamma));
    }
    let gamma = 1.0 / gamma;

    for y in 0..h {
        for x in 0..w {

            let p = try!(src.get_pixel(x, y));
            let r = (p.r as f32 / 255.0).powf(gamma) * 255.0;
            let g = (p.g as f32 / 255.0).powf(gamma) * 255.0;
            let b = (p.b as f32 / 255.0).powf(gamma) * 255.0;
            let a = (p.a as f32 / 255.0).powf(gamma) * 255.0;

            try!(src.set_pixel(x, y, Color::rgba(r as u8, g as u8, b as u8, a as u8)));

        }
    }

    Ok(())
}

/// Turn into grayscale image.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::grayscale(&mut image).unwrap();
/// raster::save(&image, "tests/out/test_filter_grayscale.jpg").unwrap();
/// ```
///
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_grayscale.jpg)
///
pub fn grayscale(mut src: &mut Image) -> RasterResult<()>{
    let w: i32 = src.width;
    let h: i32 = src.height;

    for y in 0..h {
        for x in 0..w {

            let p = try!(src.get_pixel(x, y));
            let gray = (p.r as f32 * 0.3) + (p.g as f32 * 0.59) + (p.b as f32 * 0.11);

            try!(src.set_pixel(x, y, Color::rgba(gray as u8, gray as u8, gray as u8, gray as u8)));

        }
    }

    Ok(())
}

/// Change saturation.
///
/// Pass a float value for sat. < 0.0 to decrease and > 0.0 to increase. Eg 0.5 for 50% increase in saturation.
///
/// Note: Saturation does not look good at the moment.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// // Create image from file
/// let mut image = raster::open("tests/in/sample.png").unwrap();
/// filter::saturation(&mut image, 0.5).unwrap();
/// raster::save(&image, "tests/out/test_filter_saturation.jpg").unwrap();
/// ```
///
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.png)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_saturation.jpg)
///
pub fn saturation(mut src: &mut Image, sat: f32) -> RasterResult<()>{
    let w: i32 = src.width;
    let h: i32 = src.height;

    for y in 0..h {
        for x in 0..w {

            let p = try!(src.get_pixel(x, y));
            let hsv = Color::to_hsv(p.r, p.g, p.b);
            let s = hsv.1;
            let factor = (100.0 - s) * sat; // use % remaining
            let mut new_s = s + factor;
            if new_s > 100.0 {
                new_s = 100.0;
            } else if new_s < 0.0 {
                new_s = 0.0;
            }
            let rgb = Color::to_rgb(hsv.0, new_s, hsv.2);

            try!(src.set_pixel(x, y, Color::rgb(rgb.0, rgb.1, rgb.2)));

        }
    }

    Ok(())
}

/// Apply sharpen.
///
/// # Examples
/// ```
/// use raster::filter;
///
/// // Create image from file
/// let mut image = raster::open("tests/in/sample.jpg").unwrap();
/// filter::sharpen(&mut image).unwrap();
/// raster::save(&image, "tests/out/test_filter_sharpen.jpg").unwrap();
/// ```
/// ### Before
/// ![](https://kosinix.github.io/raster/in/sample.jpg)
///
/// ### After
/// ![](https://kosinix.github.io/raster/out/test_filter_sharpen.jpg)
///
pub fn sharpen(mut src: &mut Image) -> RasterResult<()>{
    let matrix: [[i32; 3]; 3] = [
        [0, -1, 0],
        [-1, 5,-1],
        [0, -1, 0]
    ];

    convolve(src, matrix, 1)
}


// Private functions

// Box
fn blur_box(mut src: &mut Image) -> RasterResult<()>{
    let matrix: [[i32; 3]; 3] = [
        [1,1,1],
        [1,1,1],
        [1,1,1]
    ];

    convolve(src, matrix, 9)
}

// Gaussian
fn blur_gaussian(mut src: &mut Image) -> RasterResult<()>{
    let matrix: [[i32; 3]; 3] = [
        [1,2,1],
        [2,4,2],
        [1,2,1]
    ];

    convolve(src, matrix, 16)
}