IOS 8 Core Image saves image section through Swift

I am using the CoreImage Framework to detect a business card. When I detect a rectangle (CIDetectorTypeRectangle), I overlay with this method:

func drawOverlay(image: CIImage, topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage { var overlay = CIImage(color: CIColor(red: 0, green: 0, blue: 1.0, alpha: 0.3)) overlay = overlay.imageByCroppingToRect(image.extent()) overlay = overlay.imageByApplyingFilter("CIPerspectiveTransformWithExtent", withInputParameters: [ "inputExtent": CIVector(CGRect: image.extent()), "inputTopLeft": CIVector(CGPoint: topLeft), "inputTopRight": CIVector(CGPoint: topRight), "inputBottomLeft": CIVector(CGPoint: bottomLeft), "inputBottomRight": CIVector(CGPoint: bottomRight) ]) return overlay.imageByCompositingOverImage(image) } 

Now I need to automatically display the selected area and save it. Does anyone know how to do this? Thanks!

+5
source share
1 answer

I have found a solution!

 func cropBusinessCardForPoints(image: CIImage, topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage { var businessCard: CIImage businessCard = image.imageByApplyingFilter("CIPerspectiveTransformWithExtent", withInputParameters: [ "inputExtent": CIVector(CGRect: image.extent()), "inputTopLeft": CIVector(CGPoint: topLeft), "inputTopRight": CIVector(CGPoint: topRight), "inputBottomLeft": CIVector(CGPoint: bottomLeft), "inputBottomRight": CIVector(CGPoint: bottomRight) ]) businessCard = image.imageByCroppingToRect(businessCard.extent()) return businessCard } 

Using:

 //Variables var context: CIContext! var orientation: UIImageOrientation = UIImageOrientation.Right override func viewDidLoad() { super.viewDidLoad() //Initialize the CIContext context = CIContext(options:nil) ... } 

When a rectangle is found:

 //... let businessCardImage = cropBusinessCardForPoints(image, topLeft: feature.topLeft, topRight: feature.topRight, bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight) //Convert CIImage to CGImage let cgimg = context.createCGImage(businessCardImage, fromRect: businessCardImage.extent()) //Convert CGImage to UIImage let newImage = UIImage(CGImage: cgimg, scale:1, orientation: orientation) 
+1
source

Source: https://habr.com/ru/post/1205353/


All Articles