11

Go プログラミング言語でカラー .png ファイルを読み込み、8 ビットのグレースケール イメージとして出力するにはどうすればよいですか?

4

5 に答える 5

14

以下のプログラムは、入力ファイル名と出力ファイル名を取ります。入力ファイルを開き、デコードし、グレースケールに変換してから、出力ファイルにエンコードします。

このプログラムはPNGに固有のものではありませんが、他のファイル形式をサポートするには、正しい画像パッケージをインポートする必要があります。たとえば、JPEGサポートを追加するには、インポートリストに追加できます_ "image/jpeg"

PNGのみをサポートする場合は、 image.Decodeの代わりにimage/png.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)
}
于 2012-01-02T03:30:10.820 に答える
0

幸いなことに、これを見つけました。 https://godoc.org/github.com/harrydb/go/img/grayscale#Convert

次のように完全に機能する例:

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)
}
于 2014-11-17T14:38:02.180 に答える
-5

簡単な方法は、Intel OpenCV ライブラリ (opensource) を使用することです。Google では、opencv を使用して画像を読み取る方法を説明しています。詳細が表示されます。

于 2012-01-02T08:06:09.583 に答える