-
Notifications
You must be signed in to change notification settings - Fork 0
/
predict.go
78 lines (64 loc) · 1.86 KB
/
predict.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
package gotflite
import (
"fmt"
"github.com/disintegration/imaging"
"github.com/jdeng/gotflite/tflite"
"image"
)
type Predictor struct {
Name string
interpreter *tflite.Interpreter
imageWidth, imageHeight int
ImageProcessor func(img image.Image, width, height int) image.Image
outputTensorIndex int
}
func NewPredictor(modelFile string, imageWidth, imageHeight int, outputTensorIndex int) (*Predictor, error) {
intp, err := tflite.NewInterpreterFromFile(modelFile, nil)
if err != nil {
return nil, err
}
if err = intp.AllocateTensors(); err != nil {
return nil, err
}
return &Predictor{interpreter: intp, imageWidth: imageWidth, imageHeight: imageHeight, outputTensorIndex: outputTensorIndex}, nil
}
func (p *Predictor) Cleanup() {
if p.interpreter != nil {
p.interpreter.Release()
p.interpreter = nil
}
}
func (p *Predictor) Run(img image.Image) (output []float32, err error) {
err = nil
if p.ImageProcessor == nil {
img = imaging.Resize(img, p.imageWidth, p.imageHeight, imaging.Linear)
} else {
img = p.ImageProcessor(img, p.imageWidth, p.imageHeight)
}
// img = imaging.Fill(img, p.imageWidth, p.imageHeight, imaging.Center, imaging.Linear)
input, err := InputFrom(img, 127.5, 127.5)
if err != nil {
fmt.Printf("Failed to load image: %v\n", err)
return
}
//get input tensor
intp := p.interpreter
tin, err := intp.GetInputTensor(0)
fmt.Printf("Input dims: %v, total: %d, type: %d, img: %d\n", tin.Dims(), tin.NumElements(), tin.Type(), len(input))
if err != nil {
fmt.Printf("Failed to get input tensor: %v\n", err)
return
}
err = tin.CopyFloats(input)
if err != nil {
fmt.Printf("Failed to copy input: %v\n", err)
return
}
err = intp.Invoke()
if err != nil {
fmt.Printf("Failed to invoke: %v\n", err)
return
}
tout, _ := intp.GetOutputTensor(p.outputTensorIndex)
return tout.ToFloats()
}