@@ -18,7 +18,8 @@ extern crate imageproc;
1818use std:: { env, f32, path:: Path } ;
1919
2020use image:: {
21- DynamicImage , GrayImage , Luma , Pixel , PixelWithColorType , Rgb , RgbImage , Rgba , RgbaImage ,
21+ DynamicImage , GenericImageView , GrayImage , Luma , Pixel , PixelWithColorType , Rgb , RgbImage ,
22+ Rgba , RgbaImage ,
2223} ;
2324
2425use imageproc:: contrast:: ThresholdType ;
@@ -55,8 +56,32 @@ trait FromDynamic {
5556}
5657
5758impl FromDynamic for GrayImage {
59+ /// According to Rec. 709
60+ /// https://en.wikipedia.org/wiki/Rec._709#The_Y'C'BC'R_color_space
61+ /// For RGBA, just ignore the Alpha channel
5862 fn from_dynamic ( image : & DynamicImage ) -> Self {
59- image. to_luma8 ( )
63+ match image {
64+ DynamicImage :: ImageRgb8 ( _) | DynamicImage :: ImageRgba8 ( _) => {
65+ let ( width, height) = image. dimensions ( ) ;
66+ let mut gray = GrayImage :: new ( width, height) ;
67+
68+ // For RGB8 format, it automatically fills the Alpha channel, which does not affect the RGB component values
69+ for ( x, y, pixel) in image. pixels ( ) {
70+ let r = pixel[ 0 ] as u32 ;
71+ let g = pixel[ 1 ] as u32 ;
72+ let b = pixel[ 2 ] as u32 ;
73+
74+ let l = ( r * 2126 + g * 7152 + b * 722 ) / 10000 ;
75+
76+ gray. put_pixel ( x, y, Luma ( [ l as u8 ] ) ) ;
77+ }
78+ gray
79+ }
80+
81+ DynamicImage :: ImageLuma8 ( gray) => gray. clone ( ) ,
82+
83+ _ => image. to_luma8 ( ) ,
84+ }
6085 }
6186}
6287
@@ -458,7 +483,8 @@ fn test_sharpen_gaussian() {
458483#[ test]
459484fn test_match_histograms ( ) {
460485 fn match_to_zebra_histogram ( image : & GrayImage ) -> GrayImage {
461- let zebra = load_image_or_panic ( Path :: new ( INPUT_DIR ) . join ( "zebra.png" ) ) . to_luma8 ( ) ;
486+ let zebra =
487+ GrayImage :: from_dynamic ( & load_image_or_panic ( Path :: new ( INPUT_DIR ) . join ( "zebra.png" ) ) ) ;
462488 imageproc:: contrast:: match_histogram ( image, & zebra)
463489 }
464490 compare_to_truth (
0 commit comments