Để chuyển ảnh RGB sang ảnh mức xám, ta cần chuyển ảnh RGB về hệ màu 8 bit. Tiếp theo, sử dụng công thức bên dưới để tính được giá trị mức xám :
I(x,y) = Red(x, y)*0.299 + Green(x, y)*0.587 + Blue(x, y)*0.114
Với I(x,y) là một điểm ảnh.
Khi các điểm ảnh có R,G,B bằng nhau thì ảnh đó được gọi là ảnh mức xám.
Code cho demo chuyển ảnh RGB sang ảnh mức xám sử dụng Lockbits:
unsafe Bitmap rgb2gray(Bitmap bmp) { int w = bmp.Width; int h = bmp.Height; Bitmap kq = new Bitmap(w, h, PixelFormat.Format8bppIndexed); BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, bmp.PixelFormat); BitmapData ndata = kq.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, kq.PixelFormat); for (int y = 0; y < h; y++) { byte* o = (byte*)data.Scan0 + (y * data.Stride); byte* n = (byte*)ndata.Scan0 + (y * ndata.Stride); for (int x = 0; x < w; x++) { n[x] = (byte)(o[x + 3] * .114 + o[x * 3 + 1] * .587 + o[x * 3 + 2] * .299); } } kq.UnlockBits(ndata); bmp.UnlockBits(data); ColorPalette cp = kq.Palette; for (int i = 0; i < 256; i++) { cp.Entries[i] = Color.FromArgb(i, i, i); } kq.Palette = cp; return kq; }Chúc các bạn thành công !
0 comments:
Post a Comment