2016-01-21 19 views
5

Nella mia app ho implementato un CIDetector per rilevare i rettangoli su un'immagine, ma ora come posso utilizzare il reso CGPoint per ritagliare l'immagine in modo che possa visualizzarla?CIDetector Perspective And Crop in Swift

Per la prospettiva ho provato ad applicare il filtro CIPerspectiveCorrection, ma non sono riuscito a farlo funzionare.

Ho cercato in giro e ho trovato alcuni indizi ma non ho trovato una soluzione in Swift.

Come utilizzare i dati forniti dallo CIDetector (rettangolo rilevato) per correggere la prospettiva e ritagliare la mia immagine?

Per tutti coloro che potrebbero non avere familiarità con ciò che restituisce CIDetectorTypeRectangle: restituisce 4 CGPoint in basso a sinistra, in basso a destra, in alto a sinistra, in alto a destra.

risposta

8

Ecco cosa ha funzionato:

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) 


     ]) 

} 

Ovunque rilevare il rettangolo:

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