2016-12-27 1 views
-1

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) 
} 

저는 매우 신감이 나네요. 제안이나 도움을 주시면 감사하겠습니다.

+0

[이] (https://maxhalford.github.io/blog/halftoning-1/) 문서를보십시오. –

답변

2

Atomic_alarm이 지적했듯이 https://maxhalford.github.io/blog/halftoning-1/은이를 간결하게 설명합니다.

내가 제대로 이해하면 파일 열기 및 생성에 대한 질문이됩니다. 당신이 마지막으로, 다음 grayscaled 이미지, image.Gray로 변환 할 수 있습니다, 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 구조체에 Decode 열린 fileimage 패키지를 사용하는 것입니다

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

Inbe : 디스크에 보내는 파일에 이미지를 작성하거나 인코딩 twile infile opening 및 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을 사용하지 않고 하드 코드의 파일 이름을 프로그램에 사용합니다.

+0

맞습니다. 제가 여기서 고민하고있는 것은 위의 코드가 "1"또는 "2"를 "file.png"으로 대체 할 때 파일에서 읽는 방법입니다. 정수 슬라이스 인덱스 "1.png" ' – CS456

+0

Args에 대해 묻고 있습니까? "Args는 프로그램 이름으로 시작하는 명령 줄 인수를 보유합니다."찾고있는 내용이 맞다면 대답을 업데이트했습니다. – Nevermore

+0

알았어, 명확히 해줘서 고맙지 만, 이제는 파일 이름에 하드 코딩을하고, 내가 제공 한 것을 파일을 입력하는 방법을 변경해야 할 필요가 있습니다. – CS456

관련 문제