1 string imgpname = @ "005"; 2 image = image. fromfile (@ "G: \" + imgpname + @". jpg "); 3 image IMG = (image) image. clone (); 4 bitmap BMP = new Bitmap (image) image. clone (); 5 Int gray = 0; 6 graphics G = graphics. fromimage (image); 7 int sum = 0; 8 int [] ZF = new int [1, 256]; // gray array 9 10 # region gray average 11 for (INT x = 0; x <BMP. width; X ++) 12 {13 for (INT y = 0; y <BMP. height; y ++) 14 {15 // grayscale algorithm 16 gray = (BMP. getpixel (x, y ). R * 299 + BMP. getpixel (x, y ). g * 587 + BMP. getpixel (x, y ). B * 114 + 500)/1000; 17 ZF [Gray] ++; 18 sum + = gray; 19} 20} 21 int AVG = sum/(BMP. width * BMP. height); 22 # endregion23 24 # region uses the obtained gray average value as the threshold value, and binarization the image for 25 for (INT x = 0; x <BMP. width; X ++) 26 {27 for (INT y = 0; y <BMP. height; y ++) 28 {29 gray = (BMP. getpixel (x, y ). R * 299 + BMP. getpixel (x, y ). g * 587 + BMP. getpixel (x, Y ). B * 114 + 500)/1000; 30 ZF [Gray] ++; 31 sum + = gray; 32 color = new color (); 33 If (gray> avg) 34 {35 color = color. fromargb (255,255,255); 36} 37 else38 {39 color = color. fromargb (0, 0, 0); 40} 41g. drawline (new pen (color, 1), X, Y, x + 1, Y + 1 ); 42} 43} 44 # endregion45 46 # region histogram drawing 47 graphics Gg = graphics. fromimage (IMG); 48 // string k = (INT) (BMP. height * 0.5)/ZF. max ()). tostring (); 49 for (INT I = 0; I <ZF. length; I ++) 50 {51 pen P = new pen (color. red, 1); 52 GG. drawline (P, I, 0, I, ZF [I]); 53} 54 # endregion55 56 IMG. save (@ "G: \" + imgpname + @ "图 .jpg"); 57 GG. dispose (); 58 image. save (@ "G: \" + imgpname + @ "binarization graph .jpg"); 59 image. dispose (); 60g. dispose (); 61 MessageBox. show ("OK! \ Ngray_avg: "+ avg); // grayscale Average Value