我的应用程序
我正在编写一个需要将 RGB 转换为灰度图像的应用程序。转换有效,但转换 3648 * 2736 像素的图像大约需要 7 秒。我知道 set 和 getpixel 需要一些时间。但我认为如果你使用 Lockbits,即使图像不小,也不应该花这么长时间。(如果有错请纠正我)。也许我只是在我的代码中犯了一个致命的错误。
编码
public static long ConvertToGrayScaleV2(Bitmap imageColor, bool useHDTVConversion)
{
Stopwatch stpw = new Stopwatch();
stpw.Start();
System.Drawing.Imaging.BitmapData imageColorData = imageColor.LockBits(new Rectangle(new Point(0, 0), imageColor.Size),
System.Drawing.Imaging.ImageLockMode.ReadWrite, imageColor.PixelFormat);
IntPtr PtrColor = imageColorData.Scan0;
int strideColor = imageColorData.Stride;
byte[] byteImageColor = new byte[Math.Abs(strideColor) * imageColor.Height];
System.Runtime.InteropServices.Marshal.Copy(PtrColor, byteImageColor, 0, Math.Abs(strideColor) * imageColor.Height);
int bytesPerPixel = getBytesPerPixel(imageColor);
byte value;
if (bytesPerPixel == -1)
throw new Exception("Can't get bytes per pixel because it is not defined for this image format.");
for (int x = 0, position; x < imageColor.Width * imageColor.Height; x++)
{
position = x * bytesPerPixel;
if (useHDTVConversion)
{
value = (byte)(byteImageColor[position] * 0.0722 + byteImageColor[position + 1] * 0.7152 + byteImageColor[position + 2] * 0.2126);
}
else
{
value = (byte)(byteImageColor[position] * 0.114 + byteImageColor[position + 1] * 0.587 + byteImageColor[position + 2] * 0.299);
}
byteImageColor[position] = value;
byteImageColor[position+1] = value;
byteImageColor[position+2] = value;
}
System.Runtime.InteropServices.Marshal.Copy(byteImageColor, 0, PtrColor, Math.Abs(strideColor) * imageColor.Height);
imageColor.UnlockBits(imageColorData);
stpw.Stop();
return stpw.ElapsedMilliseconds;
}
public static int getBytesPerPixel(Image img)
{
switch (img.PixelFormat)
{
case System.Drawing.Imaging.PixelFormat.Format16bppArgb1555: return 2;
case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale: return 2;
case System.Drawing.Imaging.PixelFormat.Format16bppRgb555: return 2;
case System.Drawing.Imaging.PixelFormat.Format16bppRgb565: return 2;
case System.Drawing.Imaging.PixelFormat.Format1bppIndexed: return 1;
case System.Drawing.Imaging.PixelFormat.Format24bppRgb: return 3;
case System.Drawing.Imaging.PixelFormat.Format32bppArgb: return 4;
case System.Drawing.Imaging.PixelFormat.Format32bppPArgb: return 4;
case System.Drawing.Imaging.PixelFormat.Format32bppRgb: return 4;
case System.Drawing.Imaging.PixelFormat.Format48bppRgb: return 6;
case System.Drawing.Imaging.PixelFormat.Format4bppIndexed: return 1;
case System.Drawing.Imaging.PixelFormat.Format64bppArgb: return 8;
case System.Drawing.Imaging.PixelFormat.Format64bppPArgb: return 8;
case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: return 1;
default: return -1;
}
}