【问题标题】:How to convert image.RGBA (image.Image) to image.Paletted?如何将 image.RGBA (image.Image) 转换为 image.Paletted?
【发布时间】:2016-03-07 18:04:21
【问题描述】:

我正在尝试从一系列任意非调色图像创建动画 GIF。为了创建调色板图像,我需要以某种方式提出调色板。

// RGBA, etc. images from somewhere else
var frames []image.Image

outGif := &gif.GIF{}
for _, simage := range frames {
  // TODO: Convert image to paletted image
  // bounds := simage.Bounds()
  // palettedImage := image.NewPaletted(bounds, ...)

  // Add new frame to animated GIF
  outGif.Image = append(outGif.Image, palettedImage)
  outGif.Delay = append(outGif.Delay, 0)
}
gif.EncodeAll(w, outGif)

golang stdlib 中是否有简单的方法来完成此操作?

【问题讨论】:

    标签: go gif animated-gif


    【解决方案1】:

    golang 标准库中似乎缺少一种智能生成调色板的自动方法(如果我在这里错了,请纠正我)。但是似乎有一个提供您自己的Quantizer 的存根,这使我进入了gogif 项目。 (这是image.Gif 的明显来源。)

    我能够从该项目中借用MedianCutQuantizer,此处定义:

    https://github.com/andybons/gogif/blob/master/mediancut.go

    结果如下:

    var subimages []image.Image // RGBA, etc. images from somewhere else
    
    outGif := &gif.GIF{}
    for _, simage := range subimages {
      bounds := simage.Bounds()
      palettedImage := image.NewPaletted(bounds, nil)
      quantizer := gogif.MedianCutQuantizer{NumColor: 64}
      quantizer.Quantize(palettedImage, bounds, simage, image.ZP)
    
      // Add new frame to animated GIF
      outGif.Image = append(outGif.Image, palettedImage)
      outGif.Delay = append(outGif.Delay, 0)
    }
    gif.EncodeAll(w, outGif)
    

    【讨论】:

    • 您可以将量化器移出循环,它不包含除 NumColor 之外的任何状态,因此您无需每次迭代都创建一个新状态。
    • 这是在您提出问题后创建的,但 Eric Pauley 的 go-quantize 是一个很好的工具。
    • quantizer.Quantize(palettedImage, bounds, simage, image.ZP) 这行写gif帧很慢。
    【解决方案2】:

    除了生成自己的调色板,您还可以使用预定义的 (https://golang.org/pkg/image/color/palette/)

    ...
    palettedImage := image.NewPaletted(bounds, palette.Plan9)
    draw.Draw(palettedImage, palettedImage.Rect, simage, bounds.Min, draw.Over)
    ...
    

    【讨论】:

    • 是我还是这个draw.Draw函数需要很多时间来执行!有什么解决方法吗?对于 GIF,我尝试使用多个 goroutine 对我的 GIF 进行编码,但这个绘图函数是一个瓶颈!
    • @ShubhamSharma 我在 Mac Pro 上也遇到了同样的情况
    • @ShubhamSharma 我遇到了同样的问题。事实证明,调色板可以对 Draw 中的性能产生巨大影响。使用来自 Taylor Hughes 的回答中的 gogif.MedianCutQuantizer 来获取下面的调色板给了我很大的加速。
    • darw.Draw 非常慢。抖动过程非常缓慢。虽然将 PNG 图像序列写入磁盘需要几微秒,但 gif 帧需要 5-6 秒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    相关资源
    最近更新 更多