/*Converts a RGB bitmap to YCbCr*/ private void generateYcbcrBitmap(Bitmap uncompressed, ref double[,] Y, ref double[,] Cb, ref double[,] Cr) { YCbCr[,] ycbcrPixels = new YCbCr[uncompressed.Width, uncompressed.Height]; Color pixel; RGB rgb = new RGB(); for (int y = 0; y < ycbcrPixels.GetLength(1); y++) { for (int x = 0; x < ycbcrPixels.GetLength(0); x++) { if (x / 2 >= Cb.GetLength(0) || y / 2 >= Cb.GetLength(1)) continue; pixel = uncompressed.GetPixel(x, y); rgb.setRed(pixel.R); rgb.setGreen(pixel.G); rgb.setBlue(pixel.B); ycbcrPixels[x, y] = convertRgbToYCbCr(rgb); Y[x, y] = ycbcrPixels[x, y].getY(); Cb[x/2,y/2] = ycbcrPixels[x, y].getCb(); Cr[x/2, y/2] = ycbcrPixels[x, y].getCr(); } } }
/*Converts RGB pixel to YCbCr*/ private YCbCr convertRgbToYCbCr(RGB rgb) { YCbCr output = new YCbCr(); output.setY(16+(rgb.getRed() * 0.257 + rgb.getGreen() * 0.504 + rgb.getBlue() * 0.098)); output.setCb(128+(rgb.getRed() * -0.148 + rgb.getGreen() * -0.291 + rgb.getBlue() * 0.439)); output.setCr(128+(rgb.getRed() * 0.439 + rgb.getGreen() * -0.368 + rgb.getBlue() * -0.071)); return output; }
//------------------------------------------------------------------------------------------------------------------ /** Old code for saving to custom fileType. not useable anymore. **/ public void oldSavingStuff(double[,] Y) { int width = Y.GetLength(0); int height = Y.GetLength(1); YCbCr[,] ycbcrPixels = new YCbCr[width,height]; Bitmap testBitmap = new Bitmap(width, height); //testBitmap = generateRgbBitmap(ycbcrPixels); testBitmap.Save("SubsampledImage.bmp", ImageFormat.Bmp); byte[] bytesToSave = new byte[width * height * 3 + 8]; int byteOffset = 0; RGB rgb = new RGB(); byte[] widthBytes = BitConverter.GetBytes(width); byte[] heightBytes = BitConverter.GetBytes(height); if (BitConverter.IsLittleEndian) { Array.Reverse(widthBytes); Array.Reverse(heightBytes); } //Saving image width to beginning of byte array. for (int i = 0; i < widthBytes.Length; i++) { bytesToSave[byteOffset++] = widthBytes[i]; } //saving image Height to beginning of byte array. for (int i = 0; i < heightBytes.Length; i++) { bytesToSave[byteOffset++] = heightBytes[i]; } //Saving image data to byte array. for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { rgb = convertYCbCrToRgb(1,2,3); bytesToSave[y * width + x + byteOffset++] = (byte)rgb.getRed(); bytesToSave[y * width + x + byteOffset++] = (byte)rgb.getGreen(); bytesToSave[y * width + x + byteOffset] = (byte)rgb.getBlue(); //Debug.WriteLine(uncompressed.GetPixel(x,y)); //Debug.WriteLine(testBitmap.GetPixel(x,y)); } } File.WriteAllBytes("TestFile.cmpr", bytesToSave); }