dongmou5628 2017-09-30 16:01
浏览 59

如何以goroutine的身份运行filepath.Walkfunc

I'm trying to parse a large image dataset. I'm using filepath.Walk ]and processing each file I find there. I'd like the filepath.

package main

import (
    "fmt"
    "image/color"
    "image/png"
    "math/rand"
    "os"
)

var (
    Black = color.Gray{0}
)

func getRandFloatNumber(min, max float32) float32 {
    return (rand.Float32()*2 - min) * max
}

func openImage(path string, info os.FileInfo, err error) error {
    infile, _ := os.Open(path)
    defer infile.Close()
    img, err := png.Decode(infile)
    if err != nil {
        return nil
    }

    array := make([]float32, 128*128)
    for y := 0; y < 128; y++ {
        for x := 0; x < 128; x++ {
            c := color.GrayModel.Convert(img.At(x, y)).(color.Gray)
            if c == Black {
                array[x*y] = getRandFloatNumber(0.7, 0.95)
            } else {
                array[x*y] = getRandFloatNumber(0.1, 0.25)
            }
        }
    }

    fmt.Println(info.Name())

    return nil
}

How to run openImage as a gorutine? Or how to optimize this code?

  • 写回答

1条回答 默认 最新

  • duanao2688 2017-10-02 13:51
    关注

    You can't get filepath.Walk to call your function in a goroutine, but you can simply start a goroutine in your WalkFunc.

    package main
    
    import (
        "os"
        "path/filepath"
    )
    
    func main() {
        filepath.Walk("/my/dir", func(path string, info os.FileInfo, err error) error {
                if err != nil {
                        return err
                }
    
                if info.IsDir() {
                        return nil
                }
    
                // Check more criteria if necessary. Also consider limiting the number
                // of concurrent goroutines.
    
                go openImage(path, info)
    
                return nil
        })
    }
    
    func openImage(path string, info os.FileInfo) {
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集