如何在Go中访问YCbCr颜色属性

huangapple go评论79阅读模式
英文:

How to access YCbCr color attributes in Go

问题

我正在迭代图像的像素,尝试获取各个颜色值并求平均值。当我这样做时:

bounds := img.Bounds()

for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  for x := bounds.Min.X; x < bounds.Max.X; x++ {
    fmt.Println(reflect.TypeOf(img.At(x, y)))     
  }
}

我得到了一亿次的 color.YCbCr。如果我不使用 reflect.TypeOf 打印,我会得到如下结果:

{154 135 124}   
{153 135 124}   
{152 135 124}   
{152 135 124}   
{151 135 124}   
{149 135 124}   
{147 135 124}   

我需要能够访问单独的 Y、Cb 和 Cr 颜色,但是当我尝试 img.At(x, y).Cbimg.At(x, y)['Y'],甚至是 img.At(x, y)[0] 时,我得到各种编译时错误,告诉我 color.Color 没有这些方法或不支持索引。

英文:

I'm iterating over an image's pixels trying to get the individual color values and average them out. When I do this:

bounds := img.Bounds()

for y := bounds.Min.Y; y &lt; bounds.Max.Y; y++ {
  for x := bounds.Min.X; x &lt; bounds.Max.X; x++ {
    fmt.Println(reflect.TypeOf(img.At(x, y)))     
  }
}

I get color.YCbCr a billion times. If I print it without reflect.TypeOf, I get a result like this:

{154 135 124}   
{153 135 124}   
{152 135 124}   
{152 135 124}   
{151 135 124}   
{149 135 124}   
{147 135 124}   

I need to be able to access the individual Y, Cb and Cr colors, but when I try img.At(x, y).Cb or img.At(x, y)[&#39;Y&#39;] or even img.At(x, y)[0], I get various compile-time errors telling me that color.Color doesn't have those methods or doesn't support indexing.

答案1

得分: 3

以下是翻译好的内容:

为了以后参考,访问底层的color.YCbCr,你只需要对值进行断言,例如:

for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
    for x := bounds.Min.X; x < bounds.Max.X; x++ {
        if c, ok := img.At(x, y).(color.YCbCr); ok {
            fmt.Println(c.Y, c.Cb, c.Cr)
        } else {
            fmt.Println(reflect.TypeOf(img.At(x, y)))
        }
    }
}
英文:

Adding this for future reference, but to access the underling color.YCbCr you just need to type assert the value, example:

for y := bounds.Min.Y; y &lt; bounds.Max.Y; y++ {
	for x := bounds.Min.X; x &lt; bounds.Max.X; x++ {
		if c, ok := img.At(x, y).(color.YCbCr); ok {
			fmt.Println(c.Y, c.Cb, c.Cr)
		} else {
			fmt.Println(reflect.TypeOf(img.At(x, y)))
		}
	}
}

答案2

得分: 0

原文已翻译如下:

原来我需要的方法是img.At(x, y).RGBA(),它分别返回这些值。

英文:

It turns out the method I needed was img.At(x, y).RGBA(), this returns those values respectively.

huangapple
  • 本文由 发表于 2015年8月26日 10:21:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/32216985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定