如何从 iPhone 相机创建灰度 CGImage?

How to create grayscale CGImage from iPhone Camera?

我想从 iPhone 的相机数据创建灰度 CGImage。我正在使用 AVFoundation 并将像素格式类型设置为

kCVPixelFormatType_420YpCbCr8BiPlanarFullRange

如果我理解正确,我应该能够从 Y 分量创建灰度图像,所以我实现了这样的委托方法:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
        let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)

        CVPixelBufferLockBaseAddress(imageBuffer, 0)
        let yPlanBufferAddress = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)

        let width = CVPixelBufferGetWidth(imageBuffer)
        let height = CVPixelBufferGetHeight(imageBuffer)        

        let data = NSData(bytes: yPlanBufferAddress, length: width * height)
        let colorSpace = CGColorSpaceCreateDeviceGray()
        let dataProvider = CGDataProviderCreateWithCFData(data)
        let imageRef = CGImageCreate(width, height, 8, 8, width * 8, colorSpace, CGBitmapInfo.ByteOrderDefault, dataProvider, nil, false, kCGRenderingIntentDefault)
        let img = UIImage(CGImage: imageRef)

        CVPixelBufferUnlockBaseAddress(imageBuffer, 0)
        delegate?.cameraController(self, didCreateImage: img)
    }

但我收到这样的奇怪图片:

有什么想法吗?

之前,我使用了一个名为 GPU Image by BradLarson 的框架来制作自定义过滤器,这是一个非常棒的框架。他们也有一些预定义的过滤器,可以使用。运行速度非常快。

试试吧!

创建灰度图像的最简单方法是使用像这样的 CIFliter,只需调整值即可获得所需的效果级别。您还可以将多个滤镜串联起来,以更好地控制对比度、曝光、颜色等。

+ (UIImage *)makeBW:(UIImage *)imageToConvert
{
    CIImage *beginImage = [CIImage imageWithCGImage:[imageToConvert CGImage]];

    CIImage *blackAndWhite = [CIFilter filterWithName:@"CIColorControls"
                                        keysAndValues:
                              kCIInputImageKey, beginImage,
                              @"inputBrightness", [NSNumber numberWithFloat:0.0],
                              @"inputContrast", [NSNumber numberWithFloat:1.12],
                              @"inputSaturation", [NSNumber numberWithFloat:0.0], nil].outputImage;

    CIContext *context = [CIContext contextWithOptions:nil];

    CGImageRef cgiimage = [context createCGImage:output fromRect:output.extent];
    UIImage *newImg = [UIImage imageWithCGImage:cgiimage];

    CGImageRelease(cgiimage);

    return newImg;
}

Y平面你必须得到'bytesPerRow',并提供给CGImageCreate。

let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane( w, 0 );

let imageRef = CGImageCreate(
    width
,   height
,   8
,   8
,   bytesPerRow