14

How do I read in a color .png file in the Go programming language, and output it as an 8-bit grayscale image?

0

5 Answers 5

15

I had this problem myself and came up with a slightly different solution. I introduced a new type, Converted, which implements image.Image. Converted consists of the original image and the color.Model.

Converted does the conversion every time it is accessed, which could give slightly worse performance if the image will be viewed multiple times, but on the other hand it is cool and composable.

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)
}
2
  • 4
    This is by far the most versatile and appropriate approach out of all of them.
    – ZorleQ
    Commented Jul 21, 2015 at 15:26
  • 1
    This should be the accepted answer. It's the Go way of doing this
    – arainone
    Commented Aug 24, 2016 at 19:32
14

The program below takes an input file name and an output file name. It opens the input file, decodes it, converts it to grayscale, then encodes it to the output file.

Thie program isn't specific to PNGs, but to support other file formats you'd have to import the correct image package. For example, to add JPEG support you could add to the imports list _ "image/jpeg".

If you only want to support PNG, then you can use image/png.Decode directly instead of image.Decode.

package main

import (
    "image"
    "image/png" // register the PNG format with the image package
    "os"
)

func main() {
    infile, err := os.Open(os.Args[1])
    if err != nil {
        // replace this with real error handling
        panic(err.String())
    }
    defer infile.Close()

    // Decode will figure out what type of image is in the file on its own.
    // We just have to be sure all the image packages we want are imported.
    src, _, err := image.Decode(infile)
    if err != nil {
        // replace this with real error handling
        panic(err.String())
    }

    // Create a new grayscale image
    bounds := src.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    gray := image.NewGray(w, h)
    for x := 0; x < w; x++ {
        for y := 0; y < h; y++ {
            oldColor := src.At(x, y)
            grayColor := image.GrayColorModel.Convert(oldColor)
            gray.Set(x, y, grayColor)
        }
    }

    // Encode the grayscale image to the output file
    outfile, err := os.Create(os.Args[2])
    if err != nil {
        // replace this with real error handling
        panic(err.String())
    }
    defer outfile.Close()
    png.Encode(outfile, gray)
}
6
  • 1
    I appreciate your quick response, however this opens an image as RGBA, as far as I know. What I need is a grayscale image, where each pixel is an 8-bit value.
    – mlbright
    Commented Jan 3, 2012 at 14:56
  • If the PNG is encoded as a grayscale image, I believe the png package will decode it to an image.Gray. If that's not the case, I think there's either an error in the image or a bug in the package.
    – Evan Shaw
    Commented Jan 4, 2012 at 0:18
  • The image is not encoded as gray scale: I want to remove color. I want to convert from RGBA in the png file, to grayscale in the Image object in Go. I actually want to lose information, sorry if I wasn't clear.
    – mlbright
    Commented Jan 5, 2012 at 5:13
  • Oh, sorry, it wasn't clear to me. I've updated my code so I think it does what you want.
    – Evan Shaw
    Commented Jan 5, 2012 at 8:10
  • 2
    The inner loop could be converted into just gray.Set(x, y, src.At(x,y)), because Set automatically does the conversion.
    – Hjulle
    Commented Jun 12, 2013 at 22:41
1

@EvanShaw 's snippet does not work now,(may be some golang API has change) I adapt it as below. sadly does output a grayscale image but the content is messy, currently I don't know why. I provide it here for your reference.

    package main

    import (
        "image"
        "image/color"
        "image/png"
        "math"
        "os"
    )

    func main() {
        filename := "dir/to/myfile/somefile.png"
        infile, err := os.Open(filename)
        if err != nil {
            // replace this with real error handling
            panic(err.Error())
        }
        defer infile.Close()

        // Decode will figure out what type of image is in the file on its own.
        // We just have to be sure all the image packages we want are imported.
        src, _, err := image.Decode(infile)
        if err != nil {
            // replace this with real error handling
            panic(err.Error())
        }

        // Create a new grayscale image
        bounds := src.Bounds()
        w, h := bounds.Max.X, bounds.Max.Y
        gray := image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
        for x := 0; x < w; x++ {
            for y := 0; y < h; y++ {
                oldColor := src.At(x, y)
                r, g, b, _ := oldColor.RGBA()
                avg := 0.2125*float64(r) + 0.7154*float64(g) + 0.0721*float64(b)
                grayColor := color.Gray{uint8(math.Ceil(avg))}
                gray.Set(x, y, grayColor)
            }
        }

        // Encode the grayscale image to the output file
        outfilename := "result.png"
        outfile, err := os.Create(outfilename)
        if err != nil {
            // replace this with real error handling
            panic(err.Error())
        }
        defer outfile.Close()
        png.Encode(outfile, gray)
    }

and by the way, golang wouldn't able to automatically decode image file, we need to directly use image type's Decode method.

2
  • I think your calculating gray is off by 0xff, the range of r, g, b is [0-0xffff]. Just use gray.Set(x, y, img.At(x, y)) is sufficient, it will handle color conversion internally. Try this bounds := img.Bounds() gray := image.NewGray(bounds) for x := bounds.Min.X; x < bounds.Max.X; x++ { for y := bounds.Min.Y; y < bounds.Max.Y; y++ { gray.Set(x, y, img.At(x, y)) } }
    – Helin Wang
    Commented Mar 9, 2016 at 7:04
  • In some cases you may need to set custom values when converting to greyscale. See -> en.wikipedia.org/wiki/… Before doing conversion @HelinWang might be right. Just right shift the rgb values by 8 like so: r >> 8.
    – foba
    Commented Apr 3, 2019 at 15:21
0

Luckily I found this, and it works! https://godoc.org/github.com/harrydb/go/img/grayscale#Convert

A fully working example as follows:

package main

import (
    "github.com/harrydb/go/img/grayscale"
    "image/jpeg"
    "image/png"
    "os"
)

func main() {
    filename := "dir/to/myfile/afile.jpg"
    infile, err := os.Open(filename)
    if err != nil {
        panic(err.Error())
    }
    defer infile.Close()

    // Must specifically use jpeg.Decode() or it 
    // would encounter unknown format error
    src, err := jpeg.Decode(infile)
    if err != nil {
        panic(err.Error())
    }



    gray := grayscale.Convert(src, grayscale.ToGrayLuminance)

    outfilename := "result.png"
    outfile, err := os.Create(outfilename)
    if err != nil {
        panic(err.Error())
    }
    defer outfile.Close()
    png.Encode(outfile, gray)
}
-5

Easy way is use Intel OpenCV library (opensource).Google how to use opencv to read images. You will get details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.