英文:
Convert PNG image to raw []byte Golang
问题
我有一个以PNG格式存储的图像,它是一个1x512维的数组。我需要将其转换为没有PNG格式的原始字节。请问如何在Go语言中将PNG转换为原始字节?
我有一些Python代码可以实现我想要的功能,但是我找不到在Go语言中实现相同功能的方法:
import (
"bytes"
"image"
_ "image/png"
"io/ioutil"
)
func PNGToRawBytes(pngData []byte) ([]byte, error) {
img, _, err := image.Decode(bytes.NewReader(pngData))
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
err = img.(image.Image).RGBA().Encode(buf)
if err != nil {
return nil, err
}
return ioutil.ReadAll(buf)
}
你可以使用上面的Go代码将PNG转换为原始字节。调用PNGToRawBytes
函数并传入PNG数据作为参数,它将返回转换后的原始字节。
英文:
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)
答案1
得分: 1
这是一个比你的解决方案更通用的解决方案。它使用图像本身的尺寸而不是硬编码的值。
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
}
英文:
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
}
答案2
得分: 0
我找到了一个解决方案:
请注意,这段代码将图像在x轴上的值复制,并且x的最大值为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
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论