iOS 8 Core Image通过Swift保存图像部分

6

我正在使用CoreImage框架来检测名片。当我检测到一个矩形(CIDetectorTypeRectangle)时,我会使用以下方法绘制覆盖层:

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

现在我需要自动拍摄选定区域的照片并保存。有人知道如何做吗?谢谢!


1
使用CGImageCreateWithImageInRect函数将其裁剪为您想要的精确部分。 - Sandeep
谢谢你的问题!现在我知道如何在Swift中裁剪CIImage了。Google拒绝帮助,苹果的网站也是如此。我尝试使用滤镜,但你可以轻松调用imageByCroppingToRect方法 :) - alexsalo
1个回答

1
我已经找到了解决方案!
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
    }

使用方法:

//Variables
    var context: CIContext!
    var orientation: UIImageOrientation = UIImageOrientation.Right



override func viewDidLoad() {
        super.viewDidLoad()

        //Initialize the CIContext
        context = CIContext(options:nil)

        ...
}

当检测到一个矩形时:
//...

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
不确定你是否这样做,但如果你想让Core Image也将图像矫正,你可以使用CIPerspectiveCorrection滤镜。效果非常好。 - Matt Long
@Ale,你的解决方案有哪些特点? - Alok Nair
但是这会裁剪成矩形。有什么办法可以裁剪到特征点吗?@AlokNair中的特征是从CIDetector检测到的对象。 - Amr Hossam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接