【问题标题】:Cropping a CIImage result in an image that is 1px too wide裁剪 CIImage 会导致图像过宽 1px
【发布时间】:2020-05-22 10:50:03
【问题描述】:

我正在尝试裁剪 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))
  }
}

这几乎可行,但结果是 1px 关闭。

输入尺寸为 1280x720,我试图获得 513x513 的输出,但我得到了 514x513。这将被馈送到 ML 模型,所以我不能承受 1px 的偏差。我也在使用 MacOS,所以我无法访问 UIKit。

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

【问题讨论】:

    标签: ios swift macos core-image


    【解决方案1】:

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

    let xOffset = ((width - size.width) / 2).rounded(.down)
    let yOffset = ((height - size.height) / 2).rounded(.down)
    

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      相关资源
      最近更新 更多