简体   繁体   中英

rotate CIImage around center with CIFilter

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!)

}

found it. I have to apply transformations to the transformation variable itself.

let transform = CGAffineTransform(translationX: self.view.frame.midX, y: self.view.frame.midY).rotate(angle: CGFloat(radians)).translatedBy(x: -self.view.frame.midX, y: -self.view.frame.midY)

Swift 5:

let image = CIImage(cvPixelBuffer: yourBuffer)
let rotatedImage = image.oriented(.right)

Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM