我会尝试在Swift中使用Core Image来复制一种面部对齐算法。然而,我已经无法在Swift中复制来自opencv的简单warpAffine。
Python代码:
使用 swift 版本(
Python代码:
print(M) #M is a matrix calculated using some face detection code
print("let transform = CGAffineTransform(a: {0[0][0]}, b: {0[1][0]}, c: {0[0][1]}, d: {0[1][1]}, tx: {0[0][2]}, ty: {0[1][2]})".format(M))
warped = cv2.warpAffine(img,M,(image_size[1],image_size[0]), borderValue = 0.0) #warped is the correctly aligned image, image_size is 112,112
我的 Swift 版本:
import UIKit
import CoreImage
let ctx = CIContext()
let image = UIImage(named: "lg.jpg")
let ciimage = CIImage(image: image!)
let transform = CGAffineTransform(a: 0.390825773796, b: -0.0333640808264, c: 0.0333640808264, d: 0.390825773796, tx: -53.8777275485, ty: -23.0859985227)
let aligned = ciimage?.transformed(by: transform)
let size = aligned!.extent
let center = CGPoint(x: size.midX, y: size.midY)
let cropRect = CGRect(x: center.x-56, y: center.y-56, width: 112, height: 112)
let cropped = aligned!.cropped(to: cropRect)
使用 swift 版本(
cropped
)所给出的图像向左旋转了几度,并且裁剪过度向下。我已经尝试重新排序变换参数,因为我猜想这就是我的错误之处。但根据opencv文档和CGAffineTransform文档的说法,参数应该是正确的。
CIFilter
?它不在你的代码中,我也不确定为什么你将其标记为 [core-image]。如果是因为你可以在CIImage
上调用某些东西...那为什么?如果你没有使用过滤器或内核 - 我认为你可能会使用 - 那为什么不只是使用一个实际的图像(无论是UIImage
还是CGImage
)呢? - user7014451