2014-04-17 242 views
2

我已成功將圖像轉換爲灰度,我想將灰度圖像還原爲RGB圖像。請幫忙。提前致謝。將RGB圖像轉換爲灰度和灰度轉換爲RGB圖像?

-(UIImage *) toGrayscale 
    { 

    const int RED = 1; 
    const int GREEN = 2; 
    const int BLUE = 3; 

     Create image rectangle with current image width/height 
     CGRect imageRect = CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale); 

     int width = imageRect.size.width; 
     int height = imageRect.size.height; 

     // the pixels will be painted to this array 
     uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t)); 

     // clear the pixels so any transparency is preserved 
     memset(pixels, 0, width * height * sizeof(uint32_t)); 

     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

     // create a context with RGBA pixels 
     CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, 
                kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast); 

     // paint the bitmap to our context which will fill in the pixels array 
     CGContextDrawImage(context, CGRectMake(0, 0, width, height), [self CGImage]); 

     for(int y = 0; y < height; y++) { 
      for(int x = 0; x < width; x++) { 
       uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x]; 

       // convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale 
       uint8_t gray = (uint8_t) ((30 * rgbaPixel[RED] + 59 * rgbaPixel[GREEN] + 11 * rgbaPixel[BLUE])/100); 

       // set the pixels to gray 
       rgbaPixel[RED] = gray; 
       rgbaPixel[GREEN] = gray; 
       rgbaPixel[BLUE] = gray; 
      } 
     } 

     // create a new CGImageRef from our context with the modified pixels 
     CGImageRef image = CGBitmapContextCreateImage(context); 

     // we're done with the context, color space, and pixels 
     CGContextRelease(context); 
     CGColorSpaceRelease(colorSpace); 
     free(pixels); 

     // make a new UIImage to return 
     UIImage *resultUIImage = [UIImage imageWithCGImage:image 
                scale:self.scale 
               orientation:UIImageOrientationUp]; 

     // we're done with image now too 
     CGImageRelease(image); 

     return resultUIImage; 
} 
+2

*灰度*到* RGB圖像*? – nicael

+0

我想將灰度圖像還原爲原始圖像 – Arvind

+3

您應該保留原始圖像並且不要用新的灰度圖像「覆蓋」它。當你再次需要它時,只需使用原始圖像。 –

回答

6

要回答這個問題有關轉換,您的灰度代碼:

uint8_t gray = (uint8_t) ((30 * rgbaPixel[RED] + 59 * rgbaPixel[GREEN] + 11 * rgbaPixel[BLUE])/100); 

給人的關係:

S = 0.3R + 0.59G + 0.11B 

GO GO從RGBS涉及求解一個未知(S)與一個方程(罰款!)。 到轉換返回就像嘗試三個未知數(RGB)給出了一個不可能的方程。

一個黑客在做灰階colorisation是考慮灰度剛剛強度,並設定

R = G = B = S - 但這不會正確地恢復你的顏色(顯然)。 因此,簡而言之,轉換爲灰度是一種不可逆轉的功能,例如對一個數字進行平方(是正數還是負數?) - 信息丟失,無法檢索。