Golang实现图片分割的几种方法
Golang实现图片分割的几种方法 我有一个图像(字节切片),如何将其切割成8个部分?我是否应该直接将切片分成8等份?
4 回复
您可以使用image包来加载图像,然后使用SubImage方法获取裁剪区域并保存它们。
更多关于Golang实现图片分割的几种方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
如果你得到8份,它们就不再是"半份"了 😊
而且很难简单地说是否可以将较大的切片分成8个相等的子切片。
这完全取决于你想要得到什么样的8个"半份",以及数据在切片中的组织方式。
通常数据是按行连续存储的,所以当且仅当你的行数能被8整除时,你可以简单地通过子切片来获取图片的水平条纹。
在Go语言中,直接按字节切分图像数据通常不是正确的方法,因为图像格式(如JPEG、PNG)具有特定的编码结构和头部信息,简单切分会破坏图像格式。以下是几种实现图像分割的方法:
方法1:使用标准库image处理
package main
import (
"image"
"image/jpeg"
"os"
)
func splitImage(img image.Image, rows, cols int) []image.Image {
bounds := img.Bounds()
width := bounds.Dx() / cols
height := bounds.Dy() / rows
var parts []image.Image
for y := 0; y < rows; y++ {
for x := 0; x < cols; x++ {
rect := image.Rect(
x*width,
y*height,
(x+1)*width,
(y+1)*height,
)
part := image.NewRGBA(rect)
for py := rect.Min.Y; py < rect.Max.Y; py++ {
for px := rect.Min.X; px < rect.Max.X; px++ {
part.Set(px-rect.Min.X, py-rect.Min.Y, img.At(px, py))
}
}
parts = append(parts, part)
}
}
return parts
}
func main() {
file, _ := os.Open("input.jpg")
defer file.Close()
img, _ := jpeg.Decode(file)
parts := splitImage(img, 2, 4) // 2行4列,共8部分
for i, part := range parts {
out, _ := os.Create(fmt.Sprintf("part%d.jpg", i))
jpeg.Encode(out, part, nil)
out.Close()
}
}
方法2:使用第三方库github.com/disintegration/imaging
package main
import (
"github.com/disintegration/imaging"
)
func splitWithImaging(img image.Image, rows, cols int) []image.Image {
width := img.Bounds().Dx() / cols
height := img.Bounds().Dy() / rows
var parts []image.Image
for y := 0; y < rows; y++ {
for x := 0; x < cols; x++ {
part := imaging.Crop(img, image.Rect(
x*width,
y*height,
(x+1)*width,
(y+1)*height,
))
parts = append(parts, part)
}
}
return parts
}
方法3:处理字节数据(仅适用于原始RGB数据)
如果确实是原始RGB数据(无压缩、无头部),可以这样处理:
func splitRawRGB(data []byte, width, height, channels int) [][]byte {
partSize := (width * height * channels) / 8
parts := make([][]byte, 8)
for i := 0; i < 8; i++ {
start := i * partSize
end := start + partSize
parts[i] = data[start:end]
}
return parts
}
对于常规图像处理,推荐使用方法1或方法2,它们能正确处理图像解码和编码。直接切分字节切片会破坏图像结构,导致无法正确显示。


