Guest User

Untitled

a guest
Jan 16th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. func normalizeImage(body io.ReadCloser) (*tensorflow.Tensor, error) {
  2. var buf bytes.Buffer
  3. io.Copy(&buf, body)
  4.  
  5. tensor, err := tensorflow.NewTensor(buf.String())
  6. if err != nil {
  7. return nil, err
  8. }
  9.  
  10. graph, input, output, err := getNormalizedGraph()
  11. if err != nil {
  12. return nil, err
  13. }
  14.  
  15. session, err := tensorflow.NewSession(graph, nil)
  16. if err != nil {
  17. return nil, err
  18. }
  19.  
  20. normalized, err := session.Run(
  21. map[tensorflow.Output]*tensorflow.Tensor{
  22. input: tensor,
  23. },
  24. []tensorflow.Output{
  25. output,
  26. },
  27. nil)
  28. if err != nil {
  29. return nil, err
  30. }
  31.  
  32. return normalized[0], nil
  33. }
  34.  
  35. // Creates a graph to decode, rezise and normalize an image
  36. func getNormalizedGraph() (graph *tensorflow.Graph, input, output tensorflow.Output, err error) {
  37. s := op.NewScope()
  38. input = op.Placeholder(s, tensorflow.String)
  39. // 3 return RGB image
  40. decode := op.DecodeJpeg(s, input, op.DecodeJpegChannels(3))
  41.  
  42. // Sub: returns x - y element-wise
  43. output = op.Sub(s,
  44. // make it 224x224: inception specific
  45. op.ResizeBilinear(s,
  46. // inserts a dimension of 1 into a tensor's shape.
  47. op.ExpandDims(s,
  48. // cast image to float type
  49. op.Cast(s, decode, tensorflow.Float),
  50. op.Const(s.SubScope("make_batch"), int32(0))),
  51. op.Const(s.SubScope("size"), []int32{224, 224})),
  52. // mean = 117: inception specific
  53. op.Const(s.SubScope("mean"), float32(117)))
  54. graph, err = s.Finalize()
  55.  
  56. return graph, input, output, err
  57. }
Add Comment
Please, Sign In to add comment