C# 彩色图像到8位灰度的转换
我正在写一个应用程序,这个应用程序应该对灰度图像进行操作。我在将输入图像转换为8位灰度图像时遇到问题。我编写了一个方法,该方法假设将输入图像转换为8位图像,但它的输出甚至远不像灰度图像C# 彩色图像到8位灰度的转换,c#,C#,我正在写一个应用程序,这个应用程序应该对灰度图像进行操作。我在将输入图像转换为8位灰度图像时遇到问题。我编写了一个方法,该方法假设将输入图像转换为8位图像,但它的输出甚至远不像灰度图像 private Bitmap ConvertToGrayScale(Bitmap bitmap) { Int32 bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8; if (bytesP
private Bitmap ConvertToGrayScale(Bitmap bitmap)
{
Int32 bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;
if (bytesPerPixel == 1)
return bitmap;
Bitmap grayscaleBitmap = new Bitmap(bitmap.Width, bitmap.Height,
PixelFormat.Format8bppIndexed);
Byte[] pixelData = GetPixelData(bitmap);
Byte[] grayScalePixelData = new byte[grayscaleBitmap.Width * grayscaleBitmap.Height];
for (int i = 0; i < grayScalePixelData.Length; i++)
{
var pixelValue = (Byte)
(pixelData[i * bytesPerPixel] * 0.3 + pixelData[i * bytesPerPixel + 1] * 0.59 +
pixelData[i * bytesPerPixel + 2] * 0.11);
grayScalePixelData[i] = pixelValue;
}
Rectangle rectangle = new Rectangle(0, 0, grayscaleBitmap.Width, grayscaleBitmap.Height);
BitmapData grayscaleBitmapData = grayscaleBitmap.LockBits(rectangle, ImageLockMode.WriteOnly,
grayscaleBitmap.PixelFormat);
IntPtr pointer = grayscaleBitmapData.Scan0;
Marshal.Copy(grayScalePixelData, 0, pointer, grayScalePixelData.Length);
grayscaleBitmap.UnlockBits(grayscaleBitmapData);
grayscaleBitmap.Save(@"D:\gray.jpg");
return grayscaleBitmap;
}
有人能指出我做错了什么吗?您使用了PixelFormat.Format8Bppined。这意味着您需要提供一个颜色表。使用调色板属性来执行此操作。另请参见,您确实意识到Bitmap.Savegray.jpg实际上会保存一个png文件,对吗?@KrisVandermotten此位图。save仅用于测试目的。我将尝试实现颜色表,看看它是否有效。