将图像转换为灰度图像
问题描述:
我试图使用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)
}
我很新,去所以任何建议或帮助将不胜感激。
答
正如Atomic_alarm指出的那样,https://maxhalford.github.io/blog/halftoning-1/解释了如何简洁地做到这一点。
但是你的问题,如果我理解正确,是关于文件的打开和创建?
的第一步是使用image
包Decode
打开file
为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
}
这比赛image.Image
结构,你可以将其转换为灰度化图像,image.Gray
然后,最后,写或编码图像到盘上的传出文件:
outfile, _ := os.Create("grayscaled.png")
defer outfile.Close()
png.Encode(outfile, grayscaledImage) // grayscaledImage -> image.Gray
Inbe在infile开放和outfile创建之间,当然,必须将图像转换为灰度。再次提醒,上面的链接,你会发现这个功能,这需要一个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
)参数的切片,和后面的任何内容将与1
,2
等文件规定:
参数数量保持命令行参数,从程序名称开始。
var Args []string
所以你会运行代码,上面是这样的:
$ go run main.go infile.png outfile.png
infile.png必须是磁盘上的文件(目录内您运行从代码,或完整路径到文件)。
我上面提供的不是使用os.Args
而是硬编码将文件名放入程序中。
看[this](https://maxhalford.github.io/blog/halftoning-1/)文章。 –