我想从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)
}
但我得到这样的奇怪图片:
有什么想法吗?
答案 0 :(得分:2)
您必须为Y平面获取'bytesPerRow',并将其提供给CGImageCreate。
let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane( w, 0 );
let imageRef = CGImageCreate(
width
, height
, 8
, 8
, bytesPerRow
答案 1 :(得分:-1)
以前,我使用了一个名为GPU Image by BradLarson的框架,非常棒的一个,用于制作自定义过滤器。他们也有一些预定义的过滤器,可以使用。工作得非常快。
尝试一下!
答案 2 :(得分:-1)
创建灰度图像的最简单方法是使用这样的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;
}