【发布时间】:2017-03-02 18:31:22
【问题描述】:
我编写了一个程序,可以将 RGBA 图像顺序转换为灰度。我现在正在尝试对其进行转换,使其并行运行。
我有点理解我需要这样做,但我正在努力开始。
这是我目前所拥有的。
package main
import (
"image"
"image/color"
"image/jpeg"
"log"
"os"
)
var lum float64
type ImageSet interface {
Set(x, y int, c color.Color)
}
func rgbtogray(r uint32, g uint32, b uint32) float64{
lum = 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
return lum
}
func main() {
file, err := os.Open("flower.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()
img, err := jpeg.Decode(file)
if err != nil {
log.Fatal(os.Stderr, "%s: %v\n", "flower.jpg", err)
}
channel1 := make(chan float64)
channel2 := make(chan float64)
b := img.Bounds()
imgSet := image.NewRGBA(b)
halfImage := b.Max.X/2
fullImage := b.Max.X
for y := 0; y < b.Max.Y; y++ {
go func() {
for x := 0; x < halfImage; x++ {
oldPixel := img.At(x, y)
r, g, b, _ := oldPixel.RGBA()
channel1 <- rgbtogray(r, g, b)
pixel := color.Gray{uint8(lum / 256)}
imgSet.Set(x, y, pixel)
}
}()
go func() {
for x := halfImage; x< fullImage; x++ {
oldPixel := img.At(x, y)
r, g, b, _ := oldPixel.RGBA()
channel2 <- rgbtogray(r, g, b)
pixel := color.Gray{uint8(lum / 256)}
imgSet.Set(x, y, pixel)
}
}()
}
outFile, err := os.Create("changed.jpg")
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
jpeg.Encode(outFile, imgSet, nil)
}
这会运行,但只返回一个黑色图像。我知道我要走的路是错误的,但我不是 100% 我需要走哪条路。
我的想法是将图像从中间分割,让一个通道处理左侧的像素,一个通道处理右侧的像素。在向下移动到下一个 y 坐标之前,依此类推。
我已经尝试将我的 go 函数中的所有代码移动到我的 rgbatogray 函数中,但是我遇到了多个与传递变量等有关的错误。最好创建另一个处理拆分等的函数,因为我认为我调用我的 go 函数应该看起来像:
go func() {
channel1 <- rgbtogray(r, g, b)
}()
go func() {
channel2 <- rgbtogray(r, g, b)
}()
我不确定接下来应该采取什么步骤,因此非常感谢任何提示和帮助。
【问题讨论】:
-
首先使用竞赛检测器运行您的程序。首先,您在多个 goroutine 之间共享一个全局
lum变量,您正在关闭 goroutine 中 for 循环中的y值,您没有从任一通道读取,因此发送可以永远不会完成(不确定它们会去哪里),在尝试写入文件之前,您不会等待任何 goroutine 完成,您使用全局lum调用 Set ,这可能是任何时间的任何值,并且您将与他们进行数据竞赛,所有人都试图打电话给imgSet.Set。 -
嗨,第一步是让它成为一个局部变量?
-
我尝试将 x 的 for 循环移动到我的 rgbtogray 函数中,但变量把我搞砸了。这是正确的方法吗?
-
这里不需要通道:只需逻辑分割图像,让一个 goroutine 在图像的左侧工作,另一个 goroutine 在图像的右半部分工作。
-
@benjano:您可能不得不直接对像素数据进行操作,而不是通过
At和Set方法来通过比赛检测器。好消息是绕过接口抽象可能与增加的并行性一样获得性能提升。
标签: image go parallel-processing image-manipulation