裁剪CIImage会导致图像宽1像素

问题描述 投票:0回答:1

我正在尝试裁剪CIImage:

extension CIImage {
  func resize(size: CGSize) -> CIImage {
    // TODO: add padding instead of cropping in the image, to keep the entire input
    let scale = min(size.width, size.height) / min(extent.size.width, extent.size.height)
    let resizedImage = transformed(by: .init(scaleX: scale, y: scale))

    let width = resizedImage.extent.width
    let height = resizedImage.extent.height
    let xOffset = (CGFloat(width) - size.width) / 2.0
    let yOffset = (CGFloat(height) - size.height) / 2.0
    let rect = CGRect(x: xOffset, y: yOffset, width: size.width, height: size.height)

    return resizedImage
      .clamped(to: rect)
      .cropped(to: CGRect(x: xOffset, y: yOffset, width: size.width, height: size.height))
  }
}

这几乎可以用,但是结果差了1像素。

输入尺寸为1280x720,我正在尝试获得513x513的输出,但我得到514x513。这将被提供给ML模型,因此我不能承受1px的误差。我也在使用MacOS,因此无法访问UIKit。

[检查结果时,预览显示为513x513,但是image.extent.size为514x513,并且ML模型失败...

enter image description here

ios swift macos core-image
1个回答
0
投票

存在的问题是CGFloat它不是整数。您需要摆脱计算中生成的小数位数。在这种情况下,问题出在您的原点偏移位置。顺便说一句width它已经是CGFloat。尝试这样:

let xOffset = ((width - size.width) / 2).rounded(.down)
let yOffset = ((height - size.height) / 2).rounded(.down)
© www.soinside.com 2019 - 2024. All rights reserved.