[stackoverflow] [progress Openedge Abl] Converting Rgba Image To Grayscale Golang

Status
Not open for further replies.
B

benjano

Guest
I'm currently working on a program to convert and RGBA image to grayscale.

I asked a question earlier and was directed to the following answer - Change color of a single pixel - Go lang image

Here is my original question - Program to convert RGBA to grayscale Golang

I have edited my code so it now successfully runs - however the image outputted is not what I want. It is converted to grayscale however the pixels are all messed up making it look like noise on an old TV.

package main

import (
"image"
"image/color"
"image/jpeg"
"log"
"os"
)

type ImageSet interface {
Set(x, y int, c color.Color)
}


func main() {
file, err := os.Open("flower.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()

img, err := jpeg.Decode(file)
if err != nil {
log.Fatal(os.Stderr, "%s: %v\n", "flower.jpg", err)
}

b := img.Bounds()

imgSet := image.NewRGBA(b)
for y := 0; y < b.Max.Y; y++ {
for x := 0; x < b.Max.X; x++ {
oldPixel := img.At(x, y)
r, g, b, a:= oldPixel.RGBA()
r = (r+g+b)/3
pixel := color.RGBA{uint8(r), uint8(r), uint8(r), uint8(a)}
imgSet.Set(x, y, pixel)
}
}

outFile, err := os.Create("changed.jpg")
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
jpeg.Encode(outFile, imgSet, nil)

}


I know I haven't added in the if else statement for checking if the image can accept the Set() method, however the suggestion for simply making a new image seems to have solved this.

Any help much appreciated.

Edit:

I've added in some suggested code from the answer below:

package main

import (
//"fmt"
"image"
"image/color"
"image/jpeg"
"log"
"os"
)

type ImageSet interface {
Set(x, y int, c color.Color)
}


func main() {
file, err := os.Open("flower.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()

img, err := jpeg.Decode(file)
if err != nil {
log.Fatal(os.Stderr, "%s: %v\n", "flower.jpg", err)
}

b := img.Bounds()
imgSet := image.NewRGBA(b)
for y := 0; y < b.Max.Y; y++ {
for x := 0; x < b.Max.X; x++ {
oldPixel := img.At(x, y)
r, g, b, _ := oldPixel.RGBA()
y := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
pixel := color.Gray{uint8(y / 256)}
imgSet.Set(x, y, pixel)
}
}

outFile, err := os.Create("changed.jpg")
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
jpeg.Encode(outFile, imgSet, nil)

}


I currently get the following error.

.\rgbtogray.go:36: cannot use y (type uint32) as type int in argument to imgSet.Set


Am I missing something from the answer? Any tips appreciated.

Continue reading...
 
Status
Not open for further replies.
Top