2011-05-21 67 views
4

我使用下面的代碼將彩色圖像轉換爲灰度圖像。(iphone)灰度圖像太暗,我可以改變灰度圖像的不透明度嗎?

生成的圖像是灰色的,但太暗。
我可以改變它的不透明度嗎? (不知道的「不透明性」一詞是它的正確的字)

+ (UIImage *)convertImageToGrayScale: (UIImage*) image 
{ 
    // Create image rectangle with current image width/height                                            
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height); 

    // Grayscale color space                                                     
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 

    // Create bitmap content with current image size and grayscale colorspace                                        
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone); 

    // Draw image into current context, with specified rectangle                                            
    // using previously defined context (with grayscale colorspace)                                           
    CGContextDrawImage(context, imageRect, [image CGImage]); 

    // Create bitmap image info from pixel data in current context                                           
    CGImageRef imageRef = CGBitmapContextCreateImage(context); 

    // Create a new UIImage object                                                   
    UIImage *newImage = [UIImage imageWithCGImage:imageRef]; 

    // Release colorspace, context and bitmap information                                             
    CGColorSpaceRelease(colorSpace); 
    CGContextRelease(context); 
    CFRelease(imageRef); 

    // Return the new grayscale image                                                  
    return newImage; 
} 

回答

0

只是轉換爲灰度有時會導致你的形象太黑暗,因爲RGB->灰度轉換可能不保留luminosity(感知亮度)的圖像。您有兩種選擇:(1)在轉換爲灰度後變亮圖像(您可以嘗試simple-iphone-image-processing);和(2)轉換圖像保存亮度。

從RGB轉換爲灰度,同時保持亮度是根據下面的函數來設定灰度值(Y)的一種常見方法:

Y = 0.30×紅色+ 0.59×綠+ 0.11×藍色

這是有效的,因爲人眼感覺綠色的給定強度比相同強度的紅色或藍色(以大致該比率)更「明亮」。