首页 > 解决方案 > 即使在缩放或平移(Swift)之前和之后,也能在 UIImage 上的点处获取灰度像素值

问题描述

我想在给定的 CGPoint 处找到灰度 UIImage 的灰度值,以及在 UIImage 已缩放和/或平移时这样做。

到目前为止,我已经能够使用 CGContext 提取整个图像的灰度值,然后使用 index = x*(width图像)+ y。但是,一旦我放大了我的图像和/或在放大后平移它,我不确定如何继续。

//Converts image to list of grayscale values
func pixelValues(fromCGImage imageRef: CGImage?) -> (pixelValues: [UInt16]?, width: Int, height: Int)
{
    var width = 0
    var height = 0
    var pixelValues: [UInt16]?
    if let imageRef = imageRef {
        width = imageRef.width
        height = imageRef.height
        let bitsPerComponent = imageRef.bitsPerComponent
        let bytesPerRow = imageRef.bytesPerRow
        let totalBytes = height * width

        let colorSpace = CGColorSpaceCreateDeviceGray()
        var intensities = [UInt16](repeating: 0, count: totalBytes)

        let contextRef = CGContext(data: &intensities, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: 0)
        contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))

        pixelValues = intensities
    }

    return (pixelValues ,width, height)
}

//Returns grayscale value of image at pixel (x,y)
func getGrayValue(pixelValues: [UInt16], width: Int, x: Int, y: Int) -> UInt16 {
    let i = x*width + y
    return pixelValues[i]
}

标签: swiftxcodegrayscale

解决方案


推荐阅读