()
| 33 | ) |
| 34 | |
| 35 | func Example() { |
| 36 | // An example for using the TensorFlow Go API for image recognition |
| 37 | // using a pre-trained inception model (http://arxiv.org/abs/1512.00567). |
| 38 | // |
| 39 | // Sample usage: <program> -dir=/tmp/modeldir -image=/path/to/some/jpeg |
| 40 | // |
| 41 | // The pre-trained model takes input in the form of a 4-dimensional |
| 42 | // tensor with shape [ BATCH_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH, 3 ], |
| 43 | // where: |
| 44 | // - BATCH_SIZE allows for inference of multiple images in one pass through the graph |
| 45 | // - IMAGE_HEIGHT is the height of the images on which the model was trained |
| 46 | // - IMAGE_WIDTH is the width of the images on which the model was trained |
| 47 | // - 3 is the (R, G, B) values of the pixel colors represented as a float. |
| 48 | // |
| 49 | // And produces as output a vector with shape [ NUM_LABELS ]. |
| 50 | // output[i] is the probability that the input image was recognized as |
| 51 | // having the i-th label. |
| 52 | // |
| 53 | // A separate file contains a list of string labels corresponding to the |
| 54 | // integer indices of the output. |
| 55 | // |
| 56 | // This example: |
| 57 | // - Loads the serialized representation of the pre-trained model into a Graph |
| 58 | // - Creates a Session to execute operations on the Graph |
| 59 | // - Converts an image file to a Tensor to provide as input to a Session run |
| 60 | // - Executes the Session and prints out the label with the highest probability |
| 61 | // |
| 62 | // To convert an image file to a Tensor suitable for input to the Inception model, |
| 63 | // this example: |
| 64 | // - Constructs another TensorFlow graph to normalize the image into a |
| 65 | // form suitable for the model (for example, resizing the image) |
| 66 | // - Creates and executes a Session to obtain a Tensor in this normalized form. |
| 67 | modeldir := flag.String("dir", "", "Directory containing the trained model files. The directory will be created and the model downloaded into it if necessary") |
| 68 | imagefile := flag.String("image", "", "Path of a JPEG-image to extract labels for") |
| 69 | flag.Parse() |
| 70 | if *modeldir == "" || *imagefile == "" { |
| 71 | flag.Usage() |
| 72 | return |
| 73 | } |
| 74 | // Load the serialized GraphDef from a file. |
| 75 | modelfile, labelsfile, err := modelFiles(*modeldir) |
| 76 | if err != nil { |
| 77 | log.Fatal(err) |
| 78 | } |
| 79 | model, err := ioutil.ReadFile(modelfile) |
| 80 | if err != nil { |
| 81 | log.Fatal(err) |
| 82 | } |
| 83 | |
| 84 | // Construct an in-memory graph from the serialized form. |
| 85 | graph := tf.NewGraph() |
| 86 | if err := graph.Import(model, ""); err != nil { |
| 87 | log.Fatal(err) |
| 88 | } |
| 89 | |
| 90 | // Create a session for inference over graph. |
| 91 | session, err := tf.NewSession(graph, nil) |
| 92 | if err != nil { |
nothing calls this directly
no test coverage detected