【发布时间】:2015-05-06 04:29:52
【问题描述】:
我似乎不知道下一步该做什么。我的目标是使用图像包中的 SubImage 函数从原始图像创建所有子图像的数组。我可以在 imageSplit() 函数中对图像进行分区,并通过通道传递给 imageReceiver() 函数。
我实际上在函数 imageReceiver() 中接收数据,但我不知道如何在从 imageSplit() 函数接收到所有图像后附加到数组并使用它。
// Partitions Image
func Partition(src image.Image) []image.Image {
newImg := image.NewNRGBA64(src.Bounds())
r := newImg.Rect
dx, dy := r.Dx(), r.Dy()
// partitionNum
pNum := 3
// partition x
px, py := (dx / pNum), (dy / pNum)
imgChan := make(chan image.Image)
imgStorage := make([]image.Image, 0)
for i := 1; i < pNum; i++ {
for j := 1; j < pNum; j++ {
startX, startY := ((px * i) - px), ((py * j) - py)
endX, endY := (px * i), (py * j)
go imageSplit(imgChan, newImg, startX, startY, endX, endY)
go imageReceiver(imgChan)
}
}
return imgStorage
}
// Creates sub-images of img
func imageSplit(imgChan chan image.Image, img *image.NRGBA64, startX, startY, endX, endY int) {
r := image.Rect(startX, startY, endX, endY)
subImg := img.SubImage(r)
imgChan <- subImg
}
// Receive sub-image from channel
func imageReceiver(imgChan chan image.Image) {
img := <-imgChan
spew.Dump(img.Bounds())
}
我想创建一个 image.Image 的全局数组,但我不确定这是否是“保存”所有子图像的正确方法。
我想这有点令人困惑的原因是因为这是我第一次在 Go 中使用并发。 感谢您的帮助:)
【问题讨论】:
-
你会想要一个
sync.WaitGroup,这样Partition直到goroutines 完成或者在pNum结果中读取并在Partition中附加一秒钟才返回。但是我没有看到在这里使用 goroutines 的意义,SubImage通常很快,因为它通常只创建一个新的图像对象来共享现有图像中的像素数据(即通常没有数据复制,只是一些簿记)。 -
谢谢,但我在理解如何在我的 imageReceiver() 函数之后创建 image.Image 数组时遇到了问题……@evanmcdonnal 给出了与我的问题相关的答案。感谢 SubImage 函数的附注......我对 Go 并发非常陌生,所以认为这将是同时创建 goroutine 来分割我的图像的完美方式。