裁剪 CIImage 导致图像太宽 1px
Cropping a CIImage result in an image that is 1px too wide
我正在尝试裁剪 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 模型失败...
问题是 CGFloat
它不是整数。您需要去掉计算中生成的小数位。在这种情况下,问题出在您的原点偏移位置 199.5
。顺便说一句 width
它已经是 CGFloat
。像这样尝试:
let xOffset = ((width - size.width) / 2).rounded(.down)
let yOffset = ((height - size.height) / 2).rounded(.down)
我正在尝试裁剪 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 模型失败...
问题是 CGFloat
它不是整数。您需要去掉计算中生成的小数位。在这种情况下,问题出在您的原点偏移位置 199.5
。顺便说一句 width
它已经是 CGFloat
。像这样尝试:
let xOffset = ((width - size.width) / 2).rounded(.down)
let yOffset = ((height - size.height) / 2).rounded(.down)