0

I'm attempting to open and extract an image to a 2D uint32[][] matrix.

This is not simply extracting any data set to a 2D uint32[][] matrix as far as I can tell, because it involved the img.At() functionality.

However, for some reason I am getting into trouble with the extraction and I am not sure whether I am extracting the pixel points in the correct ordering.

My input image is this:

enter image description here

The code is as follows:

f, err := os.Open("../../images/noise.png")

if err != nil {
    t.Errorf("Error opening image: %s", err)
}

defer f.Close()

img, err := png.Decode(f)

if err != nil {
    t.Errorf("Error decoding image: %s", err)
}

// Convert the image to a grayscale image:
bounds := img.Bounds()

ex := make([][]uint32, bounds.Dy())

row := make([]uint32, bounds.Dx())

for y := 0; y < bounds.Dy(); y++ {
    ex[y] = row
}

mono := NewMonochromeExposure(ex, bounds.Dx(), bounds.Dy())

for j := 0; j < bounds.Dy(); j++ {
    for i := 0; i < bounds.Dx(); i++ {
        r, g, b, _ := img.At(i, j).RGBA()
        lum := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
        mono.Raw[j][i] = uint32(lum / 256)
    }
}

mono.Preprocess()

The Preprocess() command effectively then takes the mono.Raw uint32[][] and reconstructs an image as follows:

func (m *MonochromeExposure) Preprocess() (bytes.Buffer, error) {
    bounds := m.Image.Bounds()

    size := bounds.Size()

    gray := image.NewGray(bounds)

    setPixel := func(gray *image.Gray, x int, y int) {
        gray.SetGray(x, y, color.Gray{uint8(m.Raw[y][x])})
    }

    utils.DeferForEachPixel(size, func(x, y int) {
        setPixel(gray, x, y)
    })

    m.Image = gray

    return m.GetBuffer(m.Image)
}

Yet, I see this as my output image:

output

I'm very confused as to how the go lang image library works by the looks of things. I'm not sure if I have my bounds wrong, or similar, but essentially I can't seem to understand what I have done wrong here ... any pro-tips would be greatly appreciated!

Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76
  • You are only creating a single row slice and you set this for each element of `ex`: `ex[y] = row`. Create a separate slice for each row: `ex[y] = make([]uint32, bounds.Dx())` – icza Oct 28 '22 at 17:13

0 Answers0