I am developing a camera app and need to get realtime greyscale video from camera. I am using AVFoundation framework and set video output like this;
private func setupCamera() {
...
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String : Int(kCVPixelFormatType_32BGRA)]
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue.main)
...
}
For captureOutput
, I write like this;
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let imageBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)!
let bytesPerRow = UInt(CVPixelBufferGetBytesPerRow(imageBuffer))
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
let bitsPerCompornent = 8
var colorSpace = CGColorSpaceCreateDeviceGray()
var bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let context = CGContext(data: baseAddress, width: Int(width), height: Int(height), bitsPerComponent: Int(bitsPerCompornent), bytesPerRow: Int(bytesPerRow), space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! as CGContext
let imageRef = context.makeImage()!
let image = UIImage(cgImage: imageRef, scale: 1.0, orientation: UIImage.Orientation.up)
CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
captureImageView.image = image
}
The point is
var colorSpace = CGColorSpaceCreateDeviceGray()
var bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
The image I can get is something like 'greyscale video' but not complete video image.
How can I get complete greyscale video?
Please advise me if anyone knows the answer to get greyscale realtime video.