我有以下代码可以转换图像的像素:
使用ColorMatrix进行转换
Bitmap bmpOut = null;
if (DisplayImage == null)
{
return;
}
bmpOut = GetBitmapFromImageSoure(OriginalImage.Source);
Bitmap originalImage = bmpOut;
Bitmap adjustedImage = new Bitmap(bmpOut.Width, bmpOut.Height);
float brightness = (float)BrightnessSlider.Value;
float contrast = (float)ContrastSlider.Value;
float gamma = (float)GammaSlider.Value;
float alpha = (float)AlphaSlider.Value;
float adjustedBrightness = brightness - 1.0f;
// create matrix that will brighten and contrast the image
float[][] ptsArray ={
new float[] {contrast, 0, 0, 0, 0}, // scale red
new float[] {0, contrast, 0, 0, 0}, // scale green
new float[] {0, 0, contrast, 0, 0}, // scale blue
new float[] {0, 0, 0, alpha, 0}, // scale alpha
new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}}; // brightness
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.ClearColorMatrix();
imageAttributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap);
Graphics g = Graphics.FromImage(adjustedImage);
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, adjustedImage.Width, adjustedImage.Height)
, 0, 0, originalImage.Width, originalImage.Height,
GraphicsUnit.Pixel, imageAttributes);
this.DisplayImage.Source = ConvertToBitmapImage(adjustedImage);
更改每个像素以转换为灰度
Bitmap original = GetBitmapFromImageSoure(OriginalImage.Source);
Bitmap converted = (Bitmap)original.Clone();
System.Drawing.Color c;
for (int i = 0; i < converted.Width; i++)
{
for (int j = 0; j < converted.Height; j++)
{
c = converted.GetPixel(i, j);
byte gray = (byte)(.299 * c.R + .587 * c.G + .114 * c.B);
converted.SetPixel(i, j, System.Drawing.Color.FromArgb(gray, gray, gray));
}
}
DisplayImage.Source = ConvertToBitmapImage(converted);
第一种方法是更改由滑块控制的图像的亮度,伽玛和对比度,并立即变换图像。
第二种方法只需要一个复选框即可花相同的时间处理同一张图像。
为什么要比使用循环中的每个像素更快地使用颜色矩阵?它如何更好地工作?