I have an image in PNG format which is just an array of dimensions 1x512. I needs its raw bytes without the PNG format. How can I convert the PNG to raw bytes in Go.
I have some python code which does what I want, but I have not been able to find the same funtionality in Go:
image = Image.open(io.BytesIO(features))
array = np.frombuffer(image.tobytes(), dtype=np.float32)
CodePudding user response:
I be found a solution:
Please note that this copies the values in the image on the x-axis and the x max is 512!
const FeatureVectorDimensionLength = 512
func imageToRaw(img image.Image) [2048]byte {
var b [FeatureVectorDimensionLength*4]byte
for i := 0; i < FeatureVectorDimensionLength; i {
nrgba := img.At(i, 0).(color.NRGBA)
idx := i*4
b[idx], b[idx 1], b[idx 2], b[idx 3] = nrgba.R, nrgba.G, nrgba.B, nrgba.A
}
return b
}
CodePudding user response:
Here's a slightly more generic solution than yours. It uses the dimensions of the image itself instead of hardcoded values.
func imageToRGBA(img image.Image) []uint8 {
sz := img.Bounds()
raw := make([]uint8, (sz.Max.X-sz.Min.X)*(sz.Max.Y-sz.Min.Y)*4)
idx := 0
for y := sz.Min.Y; y < sz.Max.Y; y {
for x := sz.Min.X; x < sz.Max.X; x {
r, g, b, a := img.At(x, y).RGBA()
raw[idx], raw[idx 1], raw[idx 2], raw[idx 3] = uint8(r), uint8(g), uint8(b), uint8(a)
idx = 4
}
}
return raw
}