甚至在缩放或平移(Swift)之前和之后都在UIImage上的点获取灰度像素值

时间:2019-05-26 01:15:59

标签: swift xcode grayscale

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

到目前为止,我已经能够使用CGContext提取整个图像的灰度值,然后使用index = x给出的索引在这些灰度值的一维数组中找到点(x,y)处的灰度值。 *(图像宽度)+ 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]
}

0 个答案:

没有答案