如何获得图像上给定点(x,y)的灰度像素值?

时间:2019-05-28 00:47:15

标签: swift image-processing uiimage

我一直在尝试使用下面的代码来提取与给定图像像素相关的灰度值。我以为它可以用,但是后来我发现结果与我的图像不一致。

如何从我的pixelValues函数返回的1D数组中为(x,y)处图像的给定像素获取正确的灰度值?

我尝试使用index = x *图片宽度+ y,但这似乎不起作用。

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]
}

2 个答案:

答案 0 :(得分:0)

您的计算

  

index = x * width of image +y

处于关闭状态,如果将2D图像存储在1D数组中,则访问[x,y]处的值的正确方法是:

index = x + width of image * y

答案 1 :(得分:0)

哇。这是不好的,原因有几个。

  1. 为什么首先将宽度和高度返回给代码时返回宽度和高度?调用代码已经具有该信息。

  2. 无需将整个图像转换为灰度。将原始RGB图像转换为内存中的缓冲区。根据所使用的方法,字节可能会按照RGBA顺序排列。然后只需准确地计算像素的第一个字节的位置即可。那么bytePosition通常是(xPos * 4)+(yPos * rowWidthInBytes)

如果字节是RGBA序列,则bytePosition将指向红色字节。将该字节添加到以下两个字节中,然后除以3。...现在,该像素具有灰度值。那样简单。

相关问题