使用 golang 的 drawmask 和 draw.Over 的图像故障

Image glitch using golang's drawmask with draw.Over

我正在用 golang 重写我最初在 python 中编写的脚本。我正在尝试重新创建的功能目前采用一张图像(彩色叠加层)并将其粘贴到相同大小的背景(地图)上,透明度为 50%。由我的 python 脚本生成的所需输出是:

我写的golang代码试图在golang中复制这个,参考this Whosebug thread

在main.go

// overlayImg is type image.Image, consists of the coloured overlay
overlayImg = lib.AddMap(overlayImg)
// lib.SaveToRecords is a function that saves image.Image overlayImg to path specified by string download.FileName
lib.SaveToRecords(overlayImg, download.FileName)

包内 myproject/lib

func AddMap(i image.Image) image.Image{
    // mapFile is the background map image
    mapFile, err := os.Open("./res/map.png")
    if err != nil { panic(err) }
    mapImg, _, err := image.Decode(mapFile)
    if err != nil { panic(err) }
    mask := image.NewUniform(color.Alpha{128})

    canvas := image.NewRGBA(mapImg.Bounds())
    draw.Draw(canvas, canvas.Bounds(), mapImg, image.Point{0, 0}, draw.Src)

    draw.DrawMask(canvas, canvas.Bounds(), i, image.Point{0, 0}, mask, image.Point{0, 0}, draw.Over)

    return canvas
}

但是,生成的图像在部分彩色叠加层中带有某种 'glitch'。这种颜色故障在脚本的每个 运行 上都得到了可靠的再现,即使使用不同的叠加层也是如此(当然,地图始终保持不变)。

如何删除 'glitch'?


我尝试过的事情:


更新

我试过根据 分配 mask := image.NewUniform(color.Alpha16{32767}) 代替 mask := image.NewUniform(color.Alpha{128})。毛刺仍然出现。此外,这个故障并不像我想象的那么一致,只出现大约 10% 的时间。似乎出现故障 取决于粘贴到背景的图像内容


更新 2

最初,mapImg 是 *image.NRGBA 类型,icanvas 是 *image.RGBA 类型。再次遵循建议 ,我将 mapImg 转换为键入 *image.RGBA 以与其余部分匹配。为此,我使用了以下几行代码:

mapImg, _, err := image.Decode(mapFile)
mapImgRGBA := image.NewRGBA(mapImg.Bounds())
draw.Draw(mapImgRGBA, mapImgRGBA.Bounds(), mapImg, image.Point{0, 0}, draw.Src)
// Use mapImgRGBA in place of mapImg from here

还是不行:

感谢在 freenode #go-nuts 频道中使用 noethics 请求查看原始叠加层,我在处理图像的每一行之后生成输出时发现了问题。

问题不在于 "image/draw",而在于我用来将叠加层调整为地图尺寸的外部库,"github.com/nfnt/resize"。

调整大小前的叠加:

调整大小后的叠加层(不需要红色和黑色像素):


更新

"github.com/nfnt/resize" 甚至都不是问题。我只是使用了错误的插值算法。事实证明,双线性为我正在处理的图像提供了最佳输出。我怀疑它也是我用来编写原始脚本的库中使用的那个。