解析C#彩色图像灰度化算法的实现代码详解
程序员文章站
2023-12-18 11:54:04
代码如下所示:复制代码 代码如下: public static bitmap makeg...
代码如下所示:
public static bitmap makegrayscale(bitmap original)
{
//create a blank bitmap the same size as original
bitmap newbitmap = new bitmap(original.width, original.height);
//get a graphics object from the new image
graphics g = graphics.fromimage(newbitmap);
//create the grayscale colormatrix
system.drawing.imaging.colormatrix colormatrix = new system.drawing.imaging.colormatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
//create some image attributes
system.drawing.imaging.imageattributes attributes = new system.drawing.imaging.imageattributes();
//set the color matrix attribute
attributes.setcolormatrix(colormatrix);
//draw the original image on the new image
//using the grayscale color matrix
g.drawimage(original, new rectangle(0, 0, original.width, original.height),
0, 0, original.width, original.height, graphicsunit.pixel, attributes);
//dispose the graphics object
g.dispose();
return newbitmap;
}
复制代码 代码如下:
public static bitmap makegrayscale(bitmap original)
{
//create a blank bitmap the same size as original
bitmap newbitmap = new bitmap(original.width, original.height);
//get a graphics object from the new image
graphics g = graphics.fromimage(newbitmap);
//create the grayscale colormatrix
system.drawing.imaging.colormatrix colormatrix = new system.drawing.imaging.colormatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
//create some image attributes
system.drawing.imaging.imageattributes attributes = new system.drawing.imaging.imageattributes();
//set the color matrix attribute
attributes.setcolormatrix(colormatrix);
//draw the original image on the new image
//using the grayscale color matrix
g.drawimage(original, new rectangle(0, 0, original.width, original.height),
0, 0, original.width, original.height, graphicsunit.pixel, attributes);
//dispose the graphics object
g.dispose();
return newbitmap;
}