2015年5月11日
C#实现灰度图像”伪彩色”处理_局部彩色化
将彩色图像转换为灰度图像是一个不可逆的过程,灰度图像不可能变换为原来的彩色图像。而某些场合需要将灰度图像转变为彩色图像,伪彩色处理主要是把黑白的灰度图像或者多波段图像转换为彩色图像的技术过程,其目的是提高图像内容的可辨识度。本文实现的是将灰度图像的某个坐标范围变换为指定颜色,并非真正意义上的伪彩色。
如下图所示,今天分享的代码可将灰度图像中指定坐标范围内的图像设置为指定颜色,图像做的不太漂亮,主要是分享代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
public static Bitmap GrayArrayToColorBitmap(Byte[,] grayArray) { // 将灰度数组转换为灰度数据 Int32 PixelHeight = grayArray.GetLength(0); // 图像高度 Int32 PixelWidth = grayArray.GetLength(1); // 图像宽度 Int32 Stride = ((PixelWidth + 3) >> 2) << 2; // 跨距宽度 Byte[] Pixels = new Byte[PixelHeight * Stride]; int index = 0; for (int i = 0; i < PixelHeight; i++) { for (int j = 0; j < PixelWidth; j++) { Pixels[index++] = grayArray[i, j]; } } Bitmap bmp = new Bitmap(PixelWidth, PixelHeight, PixelFormat.Format24bppRgb); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, PixelWidth, PixelHeight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); int stride = bmpData.Stride; int offset = stride - PixelWidth * 3; IntPtr iptr = bmpData.Scan0; int scanBytes = stride * PixelHeight; int posScan = 0; int posReal = 0; byte[] pixelValues = new byte[scanBytes]; for (int x = 0; x < PixelHeight; x++) { for (int y = 0; y < PixelWidth; y++) { //将图像的左下角变为指定颜色 if ((x > (11*(PixelHeight>>4))) && (y < (PixelWidth / 6))) { pixelValues[posScan] = 0; pixelValues[posScan + 1] = 0; pixelValues[posScan + 2] = 255; posReal++; } else { pixelValues[posScan] = pixelValues[posScan + 1] = pixelValues[posScan + 2] = Pixels[posReal++]; } posScan += 3; } posScan += offset; } System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes); bmp.UnlockBits(bmpData); return bmp; } |