go - 在 Go 中将图像转换为灰度

标签 go

我正在尝试使用 Go 将图像转换为灰度图像。

我找到了下面的代码,但是,我很难理解它。

如果您能解释每个函数的作用以及定义传入和传出文件的位置,那将非常有帮助。

package main

import (
    "image"
    _ "image/jpeg" // Register JPEG format
    "image/png"    // Register PNG  format
    "image/color"
    "log"
    "os"
)

// Converted implements image.Image, so you can
// pretend that it is the converted image.
type Converted struct {
    Img image.Image
    Mod color.Model
}

// We return the new color model...
func (c *Converted) ColorModel() color.Model{
    return c.Mod
}

// ... but the original bounds
func (c *Converted) Bounds() image.Rectangle{
    return c.Img.Bounds()
}

// At forwards the call to the original image and
// then asks the color model to convert it.
func (c *Converted) At(x, y int) color.Color{
    return c.Mod.Convert(c.Img.At(x,y))
}

func main() {
    if len(os.Args) != 3 { log.Fatalln("Needs two arguments")}
    infile, err := os.Open(os.Args[1])
    if err != nil {
        log.Fatalln(err)
    }
    defer infile.Close()

    img, _, err := image.Decode(infile)
    if err != nil {
        log.Fatalln(err)
    }

    // Since Converted implements image, this is now a grayscale image
    gr := &Converted{img, color.GrayModel}
    // Or do something like this to convert it into a black and
    // white image.
    // bw := []color.Color{color.Black,color.White}
    // gr := &Converted{img, color.Palette(bw)}


    outfile, err := os.Create(os.Args[2])
    if err != nil {
        log.Fatalln(err)
    }
    defer outfile.Close()

    png.Encode(outfile,gr)
}

我是 Go 的新手,所以任何建议或帮助都将不胜感激。

最佳答案

正如 Atomic_alarm 指出的那样,https://maxhalford.github.io/blog/halftoning-1/简要说明如何执行此操作。

但您的问题是,如果我理解正确的话,是关于文件打开和创建的吗?

第一步是使用image包将打开的文件解码image.Image结构:

infile, err := os.Open("fullcolor.png")
if err != nil {
    return nil, err
}
defer infile.Close()

img, _, err := image.Decode(infile) // img -> image.Image
if err != nil {
    return nil, err
}

使用这个 Go image.Image 结构,您可以将其转换为灰度图像 image.Gray 然后,最后写入或编码 将图像放到磁盘上的传出文件中:

outfile, _ := os.Create("grayscaled.png")
defer outfile.Close()
png.Encode(outfile, grayscaledImage) // grayscaledImage -> image.Gray

当然,在打开文件和创建文件之间,您必须将图像转换为灰度。再次尝试上面的链接,您会发现这个函数,它接受一个 image.Image 并返回一个指向 image.Gray 的指针:

func rgbaToGray(img image.Image) *image.Gray {
    var (
        bounds = img.Bounds()
        gray   = image.NewGray(bounds)
    )
    for x := 0; x < bounds.Max.X; x++ {
        for y := 0; y < bounds.Max.Y; y++ {
            var rgba = img.At(x, y)
            gray.Set(x, y, rgba)
        }
    }
    return gray
}

关于您提供的代码(和您的评论),您正在使用 os.Args[1] 打开文件,并创建文件 os.Args[2]os.Args 是运行程序时传递的参数片段,0 将始终是程序本身(main),后面的内容将使用 12 等。文档指出:

Args hold the command-line arguments, starting with the program name. var Args []string

因此您可以像这样运行上面的代码:

$ go run main.go infile.png outfile.png

infile.png 必须是磁盘上的文件(在您运行代码的目录中,或文件的完整路径中)。

我上面提供的内容不使用 os.Args,而是将文件名硬编码到程序中。

关于go - 在 Go 中将图像转换为灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41350255/

相关文章:

go - 解码为结构时 JSON 输入意外结束

http - 在golang中获取TTFB(第一个字节的时间)值

go - 使用 Goroutine 对数字进行排序时出现意外结果

go - 使用mustEmbedUnimplemented ***方法的grpc

go - Couchbase群集的SearchQuery在Go客户端的v2版本上不起作用

go - 跟踪给定时间戳的当前年份和月份

go - Kubernetes 中的 NSQ 集群

go - 如何在两个自定义类型之间进行转换

Go dep 不解析 "golang.org/x/crypto"

http - GoQuery 响应代码