CIDetector Perspective and Swift Harvest

I applied the CIDetector in my application to detect rectangles in the image, but now how can I use the returned CGPoint to crop the image so that I can display it?

For perspective, I tried applying the CIPerspectiveCorrection filter, but could not get it to work.

I searched and found some clues, but couldn't find a solution in Swift.

How to use the data provided by CIDetector (detected rectangle) to correct perspectives and crop the image?

For those who may not know what the CIDetectorTypeRectangle returns: it returns 4 CGPoint bottomLeft, bottomRight, topLeft, topRight.

+5
source share
1 answer

Here's what worked:

 func flattenImage(image: CIImage, topLeft: CGPoint, topRight: CGPoint,bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage { return image.applyingFilter("CIPerspectiveCorrection", withInputParameters: [ "inputTopLeft": CIVector(cgPoint: topLeft), "inputTopRight": CIVector(cgPoint: topRight), "inputBottomLeft": CIVector(cgPoint: bottomLeft), "inputBottomRight": CIVector(cgPoint: bottomRight) ]) } 

Wherever you find your rectangle:

 UIGraphicsBeginImageContext(CGSize(width: flattenedImage!.extent.size.height, height: flattenedImage!.extent.size.width)) UIImage(ciImage:resultImage!,scale:1.0,orientation:.right).draw(in: CGRect(x: 0, y: 0, width: resultImage!.extent.size.height, height: resultImage!.extent.size.width)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() 
+8
source

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


All Articles