【问题标题】:Convert RGBA to NRGBA将 RGBA 转换为 NRGBA
【发布时间】:2016-10-16 11:05:52
【问题描述】:

我正在尝试返回已更改的像素及其颜色。以下 func 工作正常,但它没有给我所需的 255,255,255 值。是否可以将其转换为所需的格式?

我已经看过这里的文档 -> https://golang.org/pkg/image/color/

我也手动尝试了不同的转换,但我无法让它工作。有人知道如何在 golang 中转换它吗?

type Pixel struct {
    x, y  int
    r, g, b, a uint32
}

func  diffImages(imgOne *image.RGBA, imgTwo *image.RGBA) []Pixel  {
var pixels []Pixel

bounds := imgOne.Bounds()
diff := false

for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
        for x := bounds.Min.X; x < bounds.Max.X; x++ {

            r, g, b, a := imgOne.At(x, y).RGBA()
            rt, gt, bt, at := imgTwo.At(x, y).RGBA()

            if r != rt || g != gt || b != bt || a != at {
                diff=true
            }

            if diff == true {
                pixel := new(Pixel)
                pixel.x = x
                pixel.y = y
                pixel.r = rt
                pixel.g = gt
                pixel.b = bt
                pixel.a = at
                pixels = append(pixels, *pixel)
            }

            diff = false
        }
    }
return pixels
}

如果有比我愿意接受的更好或更快的方法来获得所需的输出。

注意:我是新手。

【问题讨论】:

  • 请举例说明您尝试了什么、输出了什么以及您希望看到什么。

标签: go colors


【解决方案1】:

你是这个意思吗?我做了其他重构,您的代码似乎不必要地复杂。

我没有对此进行测试,也没有测试图像。

// Pixels are pixels.
type Pixel struct {
    x, y  int
    color color.NRGBA
}

func diffImages(imgOne image.RGBA, imgTwo image.RGBA) []Pixel {
    var pixels []Pixel

    bounds := imgOne.Bounds()

    for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
        for x := bounds.Min.X; x < bounds.Max.X; x++ {

            if !reflect.DeepEqual(imgOne.Pix, imgTwo.Pix) {

                rt, gt, bt, at := imgTwo.At(x, y).RGBA()
                pixel := new(Pixel)
                pixel.x = x
                pixel.y = y
                pixel.color.R = uint8(rt)
                pixel.color.G = uint8(gt)
                pixel.color.B = uint8(bt)
                pixel.color.A = uint8(at)
                pixels = append(pixels, *pixel)
            }
        }
    }
    return pixels
}

【讨论】:

  • 谢谢。它可能很复杂,因为我只习惯于 python、ruby 和 php。这个问题对某些人来说似乎也很容易。感谢您的帮助。
  • @Dany:这是否有效,可能还有其他不正确的事情发生,因为您正在采用 alpha 预乘值,并将它们直接放入非 alpha 预乘颜色(这将将您的 Alpha 通道与 RGB 值重新相乘)
  • @JimB 它似乎正在工作,但我现在无法确定。我仍在努力学习与这个项目一起编写代码。有没有另一种方法可以将RGBA转换为NRGBA并获取发生变化的像素?
  • @Dany:alpha 通道总是 255 吗?您可以看到,如果有 alpha,则 RGBA 输出必须不同:play.golang.org/p/I0Gm--mlGk。为什么需要“转换”为 MRGBA? (假设值不应该是 NRGBA 开始)
猜你喜欢
  • 2012-04-11
  • 2014-03-01
  • 1970-01-01
  • 2012-02-04
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
相关资源
最近更新 更多