获取图像中的像素值
问题描述:
我正在计算我拍摄的照片中像素的RGB值。我有这个代码获取图像中的像素值
func getPixelColorAtLocation(context: CGContext, point: CGPoint) -> Color {
self.context = createARGBBitmapContext(imgView.image!)
let data = CGBitmapContextGetData(context)
let dataType = UnsafePointer<UInt8>(data)
let offset = 4 * ((Int(imageHeight) * Int(point.x)) + Int(point.y))
var color = Color()
color.blue = dataType[offset]
color.green = dataType[offset + 1]
color.red = dataType[offset + 2]
color.alpha = dataType[offset + 3]
color.point.x = point.x
color.point.y = point.y
但我不确定这行代表代码中的含义。
let offset = 4 * ((Int(imageHeight) * Int(point.x)) + Int(point.y))
任何帮助? 在此先感谢
答
图像是一组像素。为了得到(x,y)点的像素,您需要计算该集合的offset
。
如果使用dataType[0]
,它没有偏移量'cos指向指针所在的位置。如果你使用了dataType[10]
,这意味着你从指针所在的位置开始第10个元素。
由于这样的事实,我们有RGBA
颜色模型,您应该4
繁殖,那么你需要获得通过x
什么偏移量(这将是x
),并通过y
(这将是图像的相乘的width
通过y
,为了获得必要的列)或:
offset = x + width * y
// offset, offset + 1, offset + 2, offset + 3 <- necessary values for you
试想一下,就像你有很长的阵列,以在它的值。
如果您想象一维数组形式的二维数组的实现,这将是明确的。我希望它会帮助你。
非常感谢!感谢! – anurag