-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
123 lines (111 loc) · 2.42 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"encoding/csv"
"flag"
"fmt"
_ "image/jpeg"
_ "image/png"
"io/ioutil"
"log"
"os"
"runtime"
"runtime/pprof"
"strconv"
"strings"
"time"
"github.com/Rompei/caffe2go/c2g"
)
func loadMeans(meanFile string) ([]float32, error) {
b, err := os.Open(meanFile)
if err != nil {
return nil, err
}
r := csv.NewReader(b)
means, err := r.Read()
if err != nil {
return nil, err
}
res := make([]float32, len(means))
for i := range means {
out, err := strconv.ParseFloat(means[i], 32)
if err != nil {
return nil, err
}
res[i] = float32(out)
}
return res, nil
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
var (
modelPath string
imagePath string
labelPath string
shape uint
meanFile string
cpuProf string
memProf string
)
flag.StringVar(&modelPath, "m", "", "Path for caffemodel.")
flag.StringVar(&imagePath, "i", "", "Path for image.")
flag.StringVar(&labelPath, "l", "", "Path for labels.")
flag.StringVar(&meanFile, "mf", "", "Meanfile path")
flag.UintVar(&shape, "s", 0, "Input Shape")
flag.StringVar(&cpuProf, "cpuProf", "", "Filename for CPU profiling.")
flag.StringVar(&memProf, "memProf", "", "Filename for Memory profiling.")
flag.Parse()
if modelPath == "" || imagePath == "" || shape == 0 {
log.Fatalln("Option is not enough.")
}
var means []float32
var err error
if meanFile != "" {
means, err = loadMeans(meanFile)
if err != nil {
log.Fatalln(err)
}
}
caffe2go, err := c2g.NewCaffe2Go(modelPath)
if err != nil {
log.Fatalln(err)
}
start := time.Now()
if cpuProf != "" {
cf, err := os.Create(cpuProf)
if err != nil {
log.Fatalln(err)
}
defer cf.Close()
pprof.StartCPUProfile(cf)
}
output, err := caffe2go.Predict(imagePath, shape, means)
if err != nil {
log.Fatalln(err)
}
if memProf != "" {
pprof.StopCPUProfile()
mf, err := os.Create(memProf)
if err != nil {
log.Fatalln(err)
}
defer mf.Close()
pprof.WriteHeapProfile(mf)
}
fmt.Printf("Done in %fs\n", time.Now().Sub(start).Seconds())
if labelPath != "" {
result := make([]float32, len(output))
for i := range output {
result[i] = output[i][0][0]
}
indice := make([]int, len(result))
labelData, err := ioutil.ReadFile(labelPath)
if err != nil {
log.Fatalln(err)
}
labels := strings.Split(string(labelData), "\n")
Argsort(result, indice)
for i := range indice[:10] {
fmt.Printf("%f:%s\n", result[i], labels[indice[i]])
}
}
}