1 回答

TA貢獻1848條經(jīng)驗 獲得超10個贊
您不能使此模式高效,因為這需要對每個像素進行接口方法調(diào)用。為了快速訪問圖像數(shù)據(jù),您可以直接訪問圖像數(shù)據(jù)。以image.RGBA類型為例:
type RGBA struct {
// Pix holds the image's pixels, in R, G, B, A order. The pixel at
// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
Pix []uint8
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
Stride int
// Rect is the image's bounds.
Rect Rectangle
}
每種圖像類型的文檔包括數(shù)據(jù)布局和索引公式。Pix對于這種類型,您可以使用以下方法從切片中提取所有紅色像素:
w, h := img.Rect.Dx(), img.Rect.Dy()
pixList := make([]uint8, w*h)
for i := 0; i < w*h; i++ {
pixList[i] = img.Pix[i*4]
}
如果需要轉(zhuǎn)換其他圖像類型,可以使用現(xiàn)有的方法進行顏色轉(zhuǎn)換,但首先要斷言正確的圖像類型并使用native*At方法避免接口調(diào)用。從 YCbCr 圖像中提取近似紅色值:
w, h := img.Rect.Dx(), img.Rect.Dy()
pixList := make([]uint8, w*h)
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
r, _, _, _ := img.YCbCrAt(x, y).RGBA()
pixList[(x*h)+y] = uint8(r >> 8)
}
}
return pixList
類似于上面的 YCbCr 圖像沒有“紅色”像素(需要為每個單獨的像素計算值),調(diào)色板圖像沒有像素的單獨 RGBA 值,需要在圖像的調(diào)色板中查找。您可以更進一步并預先確定調(diào)色板顏色的顏色模型以刪除Color.RGBA()接口調(diào)用以加快速度,就像這樣:
palette := make([]*color.RGBA, len(img.Palette))
for i, c := range img.Palette {
palette[i] = c.(*color.RGBA)
}
pixList := make([]uint8, len(img.Pix))
for i, p := range img.Pix {
pixList[i] = palette[p].R
}
- 1 回答
- 0 關(guān)注
- 351 瀏覽
添加回答
舉報