iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用
iOS8 Core Image In Swift:更复杂的滤镜
iOS8 Core Image In Swift:人脸检测以及马赛克
iOS8 Core Image In Swift:视频实时滤镜
class ViewController: UIViewController , AVCaptureVideoDataOutputSampleBufferDelegate {
var captureSession: AVCaptureSession!
var previewLayer: CALayer!
......
除此之外,我还对VC实现了AVCaptureVideoDataOutputSampleBufferDelegate协议,这个会在后面说。 要使用AV框架,必须先引入库:import AVFoundation |
override func viewDidLoad() {
super.viewDidLoad()
previewLayer = CALayer()
previewLayer.bounds = CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width);
previewLayer.position = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
previewLayer.setAffineTransform(CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0)));
self.view.layer.insertSublayer(previewLayer, atIndex: 0)
setupCaptureSession()
}
func setupCaptureSession() {
captureSession = AVCaptureSession()
captureSession.beginConfiguration()
captureSession.sessionPreset = AVCaptureSessionPresetLow
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let deviceInput = AVCaptureDeviceInput.deviceInputWithDevice(captureDevice, error: nil) as AVCaptureDeviceInput
if captureSession.canAddInput(deviceInput) {
captureSession.addInput(deviceInput)
}
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey : kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
}
let queue = dispatch_queue_create("VideoQueue", DISPATCH_QUEUE_SERIAL)
dataOutput.setSampleBufferDelegate(self, queue: queue)
captureSession.commitConfiguration()
}
从这个方法开始,就算正式开始了。
我们现在完成一个session的建立过程,但这个session还没有开始工作,就像我们访问数据库的时候,要先打开数据库---然后建立连接---访问数据---关闭连接---关闭数据库一样,我们在openCamera方法里启动session:
@IBAction func openCamera(sender: UIButton) {
sender.enabled = false
captureSession.startRunning()
}
optional func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!)
这个回调就可以了:
func captureOutput(captureOutput: AVCaptureOutput!,
didOutputSampleBuffer sampleBuffer: CMSampleBuffer!,
fromConnection connection: AVCaptureConnection!) {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
CVPixelBufferLockBaseAddress(imageBuffer, 0)
let width = CVPixelBufferGetWidthOfPlane(imageBuffer, 0)
let height = CVPixelBufferGetHeightOfPlane(imageBuffer, 0)
let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0)
let lumaBuffer = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
let grayColorSpace = CGColorSpaceCreateDeviceGray()
let context = CGBitmapContextCreate(lumaBuffer, width, height, 8, bytesPerRow, grayColorSpace, CGBitmapInfo.allZeros)
let cgImage = CGBitmapContextCreateImage(context)
dispatch_sync(dispatch_get_main_queue(), {
self.previewLayer.contents = cgImage
})
}
var filter: CIFilter!
lazy var context: CIContext = {
let eaglContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2)
let options = [kCIContextWorkingColorSpace : NSNull()]
return CIContext(EAGLContext: eaglContext, options: options)
}()
实际上,通过contextWithOptions:创建的GPU的context,虽然渲染是在GPU上执行,但是其输出的image是不能显示的, 只有当其被复制回CPU存储器上时,才会被转成一个可被显示的image类型,比如UIImage。 |
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
替换为
kCVPixelFormatType_32BGRA
再把session的回调进行一些修改,变成我们熟悉的方式,就像这样:
func captureOutput(captureOutput: AVCaptureOutput!,
didOutputSampleBuffer sampleBuffer: CMSampleBuffer!,
fromConnection connection: AVCaptureConnection!) {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
// CVPixelBufferLockBaseAddress(imageBuffer, 0)
// let width = CVPixelBufferGetWidthOfPlane(imageBuffer, 0)
// let height = CVPixelBufferGetHeightOfPlane(imageBuffer, 0)
// let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0)
// let lumaBuffer = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
//
// let grayColorSpace = CGColorSpaceCreateDeviceGray()
// let context = CGBitmapContextCreate(lumaBuffer, width, height, 8, bytesPerRow, grayColorSpace, CGBitmapInfo.allZeros)
// let cgImage = CGBitmapContextCreateImage(context)
var outputImage = CIImage(CVPixelBuffer: imageBuffer)
if filter != nil {
filter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = filter.outputImage
}
let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent())
dispatch_sync(dispatch_get_main_queue(), {
self.previewLayer.contents = cgImage
})
}
这是一段拓展性、维护性都比较好的代码了:
class ViewController: UIViewController , AVCaptureVideoDataOutputSampleBufferDelegate {
@IBOutlet var filterButtonsContainer: UIView!
var captureSession: AVCaptureSession!
var previewLayer: CALayer!
var filter: CIFilter!
lazy var context: CIContext = {
let eaglContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2)
let options = [kCIContextWorkingColorSpace : NSNull()]
return CIContext(EAGLContext: eaglContext, options: options)
}()
lazy var filterNames: [String] = {
return ["CIColorInvert","CIPhotoEffectMono","CIPhotoEffectInstant","CIPhotoEffectTransfer"]
}()
......
......
filterButtonsContainer.hidden = true
......
@IBAction func openCamera(sender: UIButton) {
sender.enabled = false
captureSession.startRunning()
self.filterButtonsContainer.hidden = false
}
@IBAction func applyFilter(sender: UIButton) {
var filterName = filterNames[sender.tag]
filter = CIFilter(name: filterName)
}
......
previewLayer = CALayer()
// previewLayer.bounds = CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width);
// previewLayer.position = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
// previewLayer.setAffineTransform(CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0)));
previewLayer.anchorPoint = CGPointZero
previewLayer.bounds = view.bounds
......
现在你运行的话看到的将是方向不正确的图像。
然后我们把方向统一放到captureSession的回调中处理,修改之前写的实现:
......
var outputImage = CIImage(CVPixelBuffer: imageBuffer)
let orientation = UIDevice.currentDevice().orientation
var t: CGAffineTransform!
if orientation == UIDeviceOrientation.Portrait {
t = CGAffineTransformMakeRotation(CGFloat(-M_PI / 2.0))
} else if orientation == UIDeviceOrientation.PortraitUpsideDown {
t = CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0))
} else if (orientation == UIDeviceOrientation.LandscapeRight) {
t = CGAffineTransformMakeRotation(CGFloat(M_PI))
} else {
t = CGAffineTransformMakeRotation(0)
}
outputImage = outputImage.imageByApplyingTransform(t)
if filter != nil {
filter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = filter.outputImage
}
......
运行之后看到的效果和之前就一样了。
方向处理完后我们还要用一个实例变量保存这个outputImage,因为这里面含有图像的元数据,我们不会丢弃它:
给VC添加一个CIImage的属性:
var ciImage: CIImage!
......
if filter != nil {
filter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = filter.outputImage
}
let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent())
ciImage = outputImage
......
最后是takePicture的方法实现:
@IBAction func takePicture(sender: UIButton) {
sender.enabled = false
captureSession.stopRunning()
var cgImage = context.createCGImage(ciImage, fromRect: ciImage.extent())
ALAssetsLibrary().writeImageToSavedPhotosAlbum(cgImage, metadata: ciImage.properties())
{ (url: NSURL!, error :NSError!) -> Void in
if error == nil {
println("保存成功")
println(url)
} else {
let alert = UIAlertView(title: "错误",
message: error.localizedDescription,
delegate: nil,
cancelButtonTitle: "确定")
alert.show()
}
self.captureSession.startRunning()
sender.enabled = true
}
}
这里需要导入AssetsLibrary库:import AssetsLibrary。writeImageToSavedPhotosAlbum方法的回调 block用到了尾随闭包语法。 |
在真机上编译、运行看看吧。
注:由于我是用layer来做预览容器的,它没有autoresizingMask这样的属性,你会发现横屏的时候就显示不正常了,在iOS 8gh,你可以通过重写VC的以下方法来兼容横屏:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator
coordinator: UIViewControllerTransitionCoordinator) {
previewLayer.bounds.size = size
}
......
// Video Records
@IBOutlet var recordsButton: UIButton!
var assetWriter: AVAssetWriter?
var assetWriterPixelBufferInput: AVAssetWriterInputPixelBufferAdaptor?
var isWriting = false
var currentSampleTime: CMTime?
var currentVideoDimensions: CMVideoDimensions?
......
func movieURL() -> NSURL {
var tempDir = NSTemporaryDirectory()
let urlString = tempDir.stringByAppendingPathComponent("tmpMov.mov")
return NSURL(fileURLWithPath: urlString)
}
func checkForAndDeleteFile() {
let fm = NSFileManager.defaultManager()
var url = movieURL()
let exist = fm.fileExistsAtPath(movieURL().path!)
var error: NSError?
if exist {
fm.removeItemAtURL(movieURL(), error: &error)
println("删除之前的临时文件")
if let errorDescription = error?.localizedDescription {
println(errorDescription)
}
}
}
func createWriter() {
self.checkForAndDeleteFile()
var error: NSError?
assetWriter = AVAssetWriter(URL: movieURL(), fileType: AVFileTypeQuickTimeMovie, error: &error)
if let errorDescription = error?.localizedDescription {
println("创建writer失败")
println(errorDescription)
return
}
let outputSettings = [
AVVideoCodecKey : AVVideoCodecH264,
AVVideoWidthKey : Int(currentVideoDimensions!.width),
AVVideoHeightKey : Int(currentVideoDimensions!.height)
]
let assetWriterVideoInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: outputSettings)
assetWriterVideoInput.expectsMediaDataInRealTime = true
assetWriterVideoInput.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0))
let sourcePixelBufferAttributesDictionary = [
kCVPixelBufferPixelFormatTypeKey : kCVPixelFormatType_32BGRA,
kCVPixelBufferWidthKey : Int(currentVideoDimensions!.width),
kCVPixelBufferHeightKey : Int(currentVideoDimensions!.height),
kCVPixelFormatOpenGLESCompatibility : kCFBooleanTrue
]
assetWriterPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: assetWriterVideoInput,
sourcePixelBufferAttributes: sourcePixelBufferAttributesDictionary)
if assetWriter!.canAddInput(assetWriterVideoInput) {
assetWriter!.addInput(assetWriterVideoInput)
} else {
println("不能添加视频writer的input \(assetWriterVideoInput)")
}
}
......
if self.filter != nil {
self.filter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = self.filter.outputImage
}
// 处理录制视频
let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer)
self.currentVideoDimensions = CMVideoFormatDescriptionGetDimensions(formatDescription)
self.currentSampleTime = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer)
if self.isWriting {
if self.assetWriterPixelBufferInput?.assetWriterInput.readyForMoreMediaData == true {
var newPixelBuffer: Unmanaged<CVPixelBuffer>? = nil
CVPixelBufferPoolCreatePixelBuffer(nil, self.assetWriterPixelBufferInput?.pixelBufferPool, &newPixelBuffer)
self.context.render(outputImage,
toCVPixelBuffer: newPixelBuffer?.takeUnretainedValue(),
bounds: outputImage.extent(),
colorSpace: nil)
let success = self.assetWriterPixelBufferInput?.appendPixelBuffer(newPixelBuffer?.takeUnretainedValue(),
withPresentationTime: self.currentSampleTime!)
newPixelBuffer?.autorelease()
if success == false {
println("Pixel Buffer没有append成功")
}
}
}
let orientation = UIDevice.currentDevice().orientation
var t: CGAffineTransform!
......
autoreleasepool {
// ....
}
@IBAction func record() {
if isWriting {
self.isWriting = false
assetWriterPixelBufferInput = nil
recordsButton.enabled = false
assetWriter?.finishWritingWithCompletionHandler({[unowned self] () -> Void in
println("录制完成")
self.recordsButton.setTitle("处理中...", forState: UIControlState.Normal)
self.saveMovieToCameraRoll()
})
} else {
createWriter()
recordsButton.setTitle("停止录制...", forState: UIControlState.Normal)
assetWriter?.startWriting()
assetWriter?.startSessionAtSourceTime(currentSampleTime!)
isWriting = true
}
}
func saveMovieToCameraRoll() {
ALAssetsLibrary().writeVideoAtPathToSavedPhotosAlbum(movieURL(), completionBlock: { (url: NSURL!, error: NSError?) -> Void in
if let errorDescription = error?.localizedDescription {
println("写入视频错误:\(errorDescription)")
} else {
self.checkForAndDeleteFile()
println("写入视频成功")
}
self.recordsButton.enabled = true
self.recordsButton.setTitle("开始录制", forState: UIControlState.Normal)
})
}
保存成功后就可以删除临时文件了。
编译、运行吧:
// 标记人脸
var faceLayer: CALayer?
修改setupCaptureSession方法,在captureSession调用commitConfiguration方法之前加入以下代码:
......
// 为了检测人脸
let metadataOutput = AVCaptureMetadataOutput()
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
if captureSession.canAddOutput(metadataOutput) {
captureSession.addOutput(metadataOutput)
println(metadataOutput.availableMetadataObjectTypes)
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeFace]
}
......
// MARK: - AVCaptureMetadataOutputObjectsDelegate
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
// println(metadataObjects)
if metadataObjects.count > 0 {
//识别到的第一张脸
var faceObject = metadataObjects.first as AVMetadataFaceObject
if faceLayer == nil {
faceLayer = CALayer()
faceLayer?.borderColor = UIColor.redColor().CGColor
faceLayer?.borderWidth = 1
view.layer.addSublayer(faceLayer)
}
let faceBounds = faceObject.bounds
let viewSize = view.bounds.size
faceLayer?.position = CGPoint(x: viewSize.width * (1 - faceBounds.origin.y - faceBounds.size.height / 2),
y: viewSize.height * (faceBounds.origin.x + faceBounds.size.width / 2))
faceLayer?.bounds.size = CGSize(width: faceBounds.size.width * viewSize.height,
height: faceBounds.size.height * viewSize.width)
print(faceBounds.origin)
print("###")
print(faceLayer!.position)
print("###")
print(faceLayer!.bounds)
}
}
......
// 标记人脸
// var faceLayer: CALayer?
var faceObject: AVMetadataFaceObject?
......
// MARK: - AVCaptureMetadataOutputObjectsDelegate
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
// println(metadataObjects)
if metadataObjects.count > 0 {
//识别到的第一张脸
faceObject = metadataObjects.first as? AVMetadataFaceObject
/*
if faceLayer == nil {
faceLayer = CALayer()
faceLayer?.borderColor = UIColor.redColor().CGColor
faceLayer?.borderWidth = 1
view.layer.addSublayer(faceLayer)
}
let faceBounds = faceObject.bounds
let viewSize = view.bounds.size
faceLayer?.position = CGPoint(x: viewSize.width * (1 - faceBounds.origin.y - faceBounds.size.height / 2),
y: viewSize.height * (faceBounds.origin.x + faceBounds.size.width / 2))
faceLayer?.bounds.size = CGSize(width: faceBounds.size.height * viewSize.width,
height: faceBounds.size.width * viewSize.height)
print(faceBounds.origin)
print("###")
print(faceLayer!.position)
print("###")
print(faceLayer!.bounds)
*/
}
}
......
if self.filter != nil { // 之前做的全局滤镜
self.filter.setValue(outputImage, forKey: kCIInputImageKey)
outputImage = self.filter.outputImage
}
if self.faceObject != nil { // 脸部处理
outputImage = self.makeFaceWithCIImage(outputImage, faceObject: self.faceObject!)
}
......
func makeFaceWithCIImage(inputImage: CIImage, faceObject: AVMetadataFaceObject) -> CIImage {
var filter = CIFilter(name: "CIPixellate")
filter.setValue(inputImage, forKey: kCIInputImageKey)
// 1.
filter.setValue(max(inputImage.extent().size.width, inputImage.extent().size.height) / 60, forKey: kCIInputScaleKey)
let fullPixellatedImage = filter.outputImage
var maskImage: CIImage!
let faceBounds = faceObject.bounds
// 2.
let centerX = inputImage.extent().size.width * (faceBounds.origin.x + faceBounds.size.width / 2)
let centerY = inputImage.extent().size.height * (1 - faceBounds.origin.y - faceBounds.size.height / 2)
let radius = faceBounds.size.width * inputImage.extent().size.width / 2
let radialGradient = CIFilter(name: "CIRadialGradient",
withInputParameters: [
"inputRadius0" : radius,
"inputRadius1" : radius + 1,
"inputColor0" : CIColor(red: 0, green: 1, blue: 0, alpha: 1),
"inputColor1" : CIColor(red: 0, green: 0, blue: 0, alpha: 0),
kCIInputCenterKey : CIVector(x: centerX, y: centerY)
])
let radialGradientOutputImage = radialGradient.outputImage.imageByCroppingToRect(inputImage.extent())
if maskImage == nil {
maskImage = radialGradientOutputImage
} else {
println(radialGradientOutputImage)
maskImage = CIFilter(name: "CISourceOverCompositing",
withInputParameters: [
kCIInputImageKey : radialGradientOutputImage,
kCIInputBackgroundImageKey : maskImage
]).outputImage
}
let blendFilter = CIFilter(name: "CIBlendWithMask")
blendFilter.setValue(fullPixellatedImage, forKey: kCIInputImageKey)
blendFilter.setValue(inputImage, forKey: kCIInputBackgroundImageKey)
blendFilter.setValue(maskImage, forKey: kCIInputMaskImageKey)
return blendFilter.outputImage
}
参考资料:
1. http://weblog.invasivecode.com/post/18445861158/a-very-cool-custom-video-camera-with
2. https://developer.apple.com/library/mac/documentation/graphicsimaging/conceptual/CoreImaging/ci_intro/ci_intro.html
3. http://en.wikipedia.org/wiki/YUV