I'm trying to rotate the pixel data of a CMSampleBuffer (coming from the camera) and display it in a UIImageView. I Don't want to rotate the view itself. It has to be the actual pixel data.
I grab the feed, convert it to a CIImage and with a CIFilter I rotate it. I'm having trouble with setting the point around which it has to rotate. Right now it rotates around the lower left point. I want to rotate it around its center.
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
//create pixelbuffer
let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let context = CIContext.init(options: nil)
// calculating the radians to rotate the ciimage by
let radians : Float = atan2f(Float(boxView!.transform.b), Float(boxView!.transform.a));
//create ciimage from the pixelbuffer
let options = [kCVPixelBufferCGImageCompatibilityKey as String: true,
kCVPixelBufferCGBitmapContextCompatibilityKey as String: true,]
let ci = CIImage.init(cvPixelBuffer: pixelBuffer, options: options)
//transform filter
let filter = CIFilter.init(name: "CIAffineTransform")
//set translation point to center
var transform = CGAffineTransform(translationX: self.view.frame.midX, y: self.view.frame.midY)
//rotate
transform = CGAffineTransform(rotationAngle:CGFloat(radians))
// set translation point back again to normal
var transformBack = CGAffineTransform(translationX: -self.view.frame.midX, y: -self.view.frame.midY)
//applying the transform
transform.concatenating(transformBack)
filter!.setValue(transform, forKey: kCIInputTransformKey)
filter!.setValue(ci, forKey: kCIInputImageKey)
let output = filter?.outputImage
let img = context.createCGImage(output!, from: imageView!.frame)
// send image to be displayed
self.imageView!.image = UIImage(cgImage: img!)
}
Swift 5:
let image = CIImage(cvPixelBuffer: yourBuffer)
let rotatedImage = image.oriented(.right)
Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With