├── LICENSE ├── README.md ├── cmd ├── caffe-video │ └── main.go ├── caffe │ └── main.go ├── hello-ncs │ └── main.go └── tf-video │ └── main.go ├── go-ncs.go ├── ncs.cpp ├── ncs.go └── ncs.h /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright (c) 2018 The Hybrid Group 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-ncs 2 | 3 | This package contains Go language bindings for the Intel® Movidius™ Neural Compute Stick (NCS) [(https://developer.movidius.com/)](https://developer.movidius.com/). 4 | 5 | You must have the Intel Movidius NCS hardware in order to use this package. 6 | 7 | ## Install 8 | 9 | This package has been tested on Ubuntu 16.04 LTS and macOS "El Capitan" and "High Sierra". 10 | 11 | You must first install the NCSDK before you can use the Intel Movidius Myriad 2 Neural Compute Stick. The official SDK only supports Linux. However, the fork created by [@milosgajdos83](https://github.com/milosgajdos83) has some initial support for macOS. Sorry, no Windows yet. 12 | 13 | ### macOS 14 | 15 | The macOS support for the NCSDK currently is only for the API, not the graph compiler or other tools. To install, run the following commands: 16 | 17 | brew install coreutils opencv libusb pkg-config wget 18 | git clone https://github.com/milosgajdos83/ncsdk.git 19 | cd ncsdk 20 | git checkout macos-V1 21 | cd api/src && sudo make basicinstall 22 | 23 | ### Linux 24 | 25 | You must have OpenCV and GoCV installed in order to use the Movidius SDK with Go: 26 | 27 | https://gocv.io/getting-started/linux/ 28 | 29 | Once they are installed, you can run the following commands: 30 | 31 | git clone https://github.com/milosgajdos83/ncsdk.git 32 | cd ncsdk 33 | make install 34 | 35 | ## Compiling Models 36 | 37 | If on Linux, once you have installed the SDK you can then download and compile the graph files for the Caffe GoogLeNet example by running the following commands: 38 | 39 | cd ./examples/caffe/GoogLeNet 40 | make prototxt 41 | make caffemodel 42 | make compile 43 | 44 | This will download and compile the NCS graph file needed to run the `go-ncs` examples. 45 | 46 | ### Install the go-ncs Go package 47 | 48 | Now you can install the go-ncs Go package: 49 | 50 | go get -d -u github.com/hybridgroup/go-ncs 51 | 52 | Once you have installed `go-ncs` you can use it just like any other Golang package. 53 | 54 | ## Using 55 | 56 | Here is a very simple example of opening/closing a connection to an NCS stick: 57 | 58 | ```go 59 | package main 60 | 61 | import ( 62 | "fmt" 63 | 64 | ncs "github.com/hybridgroup/go-ncs" 65 | ) 66 | 67 | func main() { 68 | res, name := ncs.GetDeviceName(0) 69 | if res != ncs.StatusOK { 70 | fmt.Printf("NCS Error: %v\n", res) 71 | return 72 | } 73 | 74 | fmt.Println("NCS: " + name) 75 | 76 | // open device 77 | fmt.Println("Opening NCS device " + name + "...") 78 | res, stick := ncs.OpenDevice(name) 79 | if res != ncs.StatusOK { 80 | fmt.Printf("NCS Error: %v\n", res) 81 | return 82 | } 83 | 84 | // close device 85 | fmt.Println("Closing NCS device " + name + "...") 86 | res = stick.CloseDevice() 87 | if res != ncs.StatusOK { 88 | fmt.Printf("NCS Error: %v\n", res) 89 | return 90 | } 91 | } 92 | ``` 93 | 94 | There are several examples in the `cmd` directory of this repository. 95 | 96 | ## Using go-ncs with GoCV 97 | 98 | It is very useful to combine go-ncs with GoCV [(https://gocv.io)](https://gocv.io) to be able to use the video capture and processing abilities of GoCV along with the classification abilities of the NCS. Take a look at the `cmd\caffe` and `cmd\caffe-video` for examples. 99 | 100 | ## License 101 | 102 | Licensed under the Apache 2.0 license. Copyright (c) 2018 The Hybrid Group. 103 | -------------------------------------------------------------------------------- /cmd/caffe-video/main.go: -------------------------------------------------------------------------------- 1 | // How to use: 2 | // 3 | // This example opens a connection to a Movidius Neural Computer Stick (NCS) 4 | // then uses OpenCV to open a camera, and start displaying the current classification 5 | // of whatever the camera sees. 6 | // 7 | // You must have OpenCV/GoCV installed to use this example. 8 | // Run the following commands: 9 | // 10 | // go run ./cmd/caffe-video/main.go 0 0 ~/Development/ncsdk/examples/caffe/GoogLeNet/graph ~/Development/ncsdk/examples/data/ilsvrc12/synset_words.txt 11 | // 12 | package main 13 | 14 | import ( 15 | "bufio" 16 | "fmt" 17 | "image" 18 | "image/color" 19 | "io/ioutil" 20 | "os" 21 | "strconv" 22 | 23 | ncs "github.com/hybridgroup/go-ncs" 24 | "gocv.io/x/gocv" 25 | ) 26 | 27 | func main() { 28 | deviceID, _ := strconv.Atoi(os.Args[1]) 29 | cameraID, _ := strconv.Atoi(os.Args[2]) 30 | graphFileName := os.Args[3] 31 | descriptions, _ := readDescriptions(os.Args[4]) 32 | 33 | // get name of NCS stick 34 | res, name := ncs.GetDeviceName(deviceID) 35 | if res != ncs.StatusOK { 36 | fmt.Printf("NCS Error: %v\n", res) 37 | return 38 | } 39 | 40 | fmt.Println("NCS: " + name) 41 | 42 | // open NCS device 43 | fmt.Println("Opening NCS device " + name + "...") 44 | status, s := ncs.OpenDevice(name) 45 | if status != ncs.StatusOK { 46 | fmt.Printf("NCS Error: %v\n", status) 47 | return 48 | } 49 | defer s.CloseDevice() 50 | 51 | // load precompiled graph file in NCS format 52 | data, err := ioutil.ReadFile(graphFileName) 53 | if err != nil { 54 | fmt.Println("Error opening graph file:", err) 55 | return 56 | } 57 | 58 | // allocate graph on NCS stick 59 | fmt.Println("Allocating graph...") 60 | allocateStatus, graph := s.AllocateGraph(data) 61 | if allocateStatus != ncs.StatusOK { 62 | fmt.Printf("NCS Error: %v\n", allocateStatus) 63 | return 64 | } 65 | defer graph.DeallocateGraph() 66 | 67 | webcam, err := gocv.VideoCaptureDevice(cameraID) 68 | if err != nil { 69 | fmt.Printf("Error opening video capture device: %v\n", cameraID) 70 | return 71 | } 72 | defer webcam.Close() 73 | 74 | window := gocv.NewWindow("Movidius Caffe Classifier") 75 | defer window.Close() 76 | 77 | img := gocv.NewMat() 78 | defer img.Close() 79 | 80 | statusColor := color.RGBA{0, 255, 0, 0} 81 | 82 | for { 83 | if ok := webcam.Read(&img); !ok { 84 | fmt.Printf("Error cannot read device %d\n", deviceID) 85 | return 86 | } 87 | if img.Empty() { 88 | continue 89 | } 90 | 91 | // convert image to half-float blob format needed by NCS 92 | fp16data := gocv.FP16BlobFromImage(img, 1.0, image.Pt(224, 224), 0, false, false) 93 | 94 | // load image tensor into graph on NCS stick 95 | loadStatus := graph.LoadTensor(fp16data) 96 | if loadStatus != ncs.StatusOK { 97 | fmt.Println("Error loading tensor data:", loadStatus) 98 | return 99 | } 100 | 101 | // get result from NCS stick in fp16 format 102 | resultStatus, data := graph.GetResult() 103 | if resultStatus != ncs.StatusOK { 104 | fmt.Println("Error getting results:", resultStatus) 105 | return 106 | } 107 | 108 | // convert results from fp16 back to float32 109 | fp16Results, _ := gocv.NewMatFromBytes(1, len(data)/2, gocv.MatTypeCV16S, data) 110 | results := fp16Results.ConvertFp16() 111 | 112 | // determine the most probable classification 113 | _, maxVal, _, maxLoc := gocv.MinMaxLoc(results) 114 | if maxLoc.X != -1 { 115 | desc := descriptions[maxLoc.X] 116 | info := fmt.Sprintf("description: %v, maxVal: %v", desc, maxVal) 117 | gocv.PutText(&img, info, image.Pt(10, img.Rows()/2), gocv.FontHersheyPlain, 1.2, statusColor, 2) 118 | } 119 | 120 | fp16Results.Close() 121 | results.Close() 122 | 123 | window.IMShow(img) 124 | if window.WaitKey(1) >= 0 { 125 | break 126 | } 127 | } 128 | } 129 | 130 | // readDescriptions reads the descriptions from a file 131 | // and returns a slice of its lines. 132 | func readDescriptions(path string) ([]string, error) { 133 | file, err := os.Open(path) 134 | if err != nil { 135 | return nil, err 136 | } 137 | defer file.Close() 138 | 139 | var lines []string 140 | scanner := bufio.NewScanner(file) 141 | for scanner.Scan() { 142 | lines = append(lines, scanner.Text()) 143 | } 144 | return lines, scanner.Err() 145 | } 146 | -------------------------------------------------------------------------------- /cmd/caffe/main.go: -------------------------------------------------------------------------------- 1 | // How to use: 2 | // 3 | // You must have OpenCV/GoCV installed to use this example. 4 | // Run the following commands: 5 | // 6 | // source $GOPATH/src/gocv.io/x/gocv/env.sh 7 | // go run ./cmd/caffe/main.go 0 ~/Development/ncsdk/examples/caffe/GoogLeNet/graph ~/Development/ncsdk/examples/data/images/cat.jpg ~/Development/ncsdk/examples/data/ilsvrc12/synset_words.txt 8 | // 9 | package main 10 | 11 | import ( 12 | "bufio" 13 | "fmt" 14 | "image" 15 | "io/ioutil" 16 | "os" 17 | "strconv" 18 | 19 | ncs "github.com/hybridgroup/go-ncs" 20 | "gocv.io/x/gocv" 21 | ) 22 | 23 | func main() { 24 | deviceID, _ := strconv.Atoi(os.Args[1]) 25 | graphFileName := os.Args[2] 26 | imageFileName := os.Args[3] 27 | descriptions, _ := readDescriptions(os.Args[4]) 28 | 29 | // get name of NCS stick 30 | res, name := ncs.GetDeviceName(deviceID) 31 | if res != ncs.StatusOK { 32 | fmt.Printf("NCS Error: %v\n", res) 33 | return 34 | } 35 | 36 | fmt.Println("NCS: " + name) 37 | 38 | // open NCS device 39 | fmt.Println("Opening NCS device " + name + "...") 40 | status, s := ncs.OpenDevice(name) 41 | if status != ncs.StatusOK { 42 | fmt.Printf("NCS Error: %v\n", status) 43 | return 44 | } 45 | defer s.CloseDevice() 46 | 47 | // load precompiled graph file in NCS format 48 | data, err := ioutil.ReadFile(graphFileName) 49 | if err != nil { 50 | fmt.Println("Error opening graph file:", err) 51 | return 52 | } 53 | 54 | // allocate graph on NCS stick 55 | fmt.Println("Allocating graph...") 56 | allocateStatus, graph := s.AllocateGraph(data) 57 | if allocateStatus != ncs.StatusOK { 58 | fmt.Printf("NCS Error: %v\n", allocateStatus) 59 | return 60 | } 61 | defer graph.DeallocateGraph() 62 | 63 | // load image file from disk 64 | img := gocv.IMRead(imageFileName, gocv.IMReadColor) 65 | 66 | // convert image to format needed by NCS 67 | resized := gocv.NewMat() 68 | gocv.Resize(img, &resized, image.Pt(224, 224), 0, 0, gocv.InterpolationDefault) 69 | 70 | fp32Image := gocv.NewMat() 71 | resized.ConvertTo(&fp32Image, gocv.MatTypeCV32F) 72 | 73 | fp16Blob := fp32Image.ConvertFp16() 74 | 75 | // load image tensor into graph on NCS stick 76 | fmt.Println("Loading tensor...") 77 | loadStatus := graph.LoadTensor(fp16Blob.ToBytes()) 78 | if loadStatus != ncs.StatusOK { 79 | fmt.Println("Error loading tensor data:", loadStatus) 80 | return 81 | } 82 | 83 | // get result from NCS stick in fp16 format 84 | resultStatus, data := graph.GetResult() 85 | if resultStatus != ncs.StatusOK { 86 | fmt.Println("Error getting results:", resultStatus) 87 | return 88 | } 89 | 90 | // convert results from fp16 back to float32 91 | fp16Results, err := gocv.NewMatFromBytes(1, len(data)/2, gocv.MatTypeCV16S, data) 92 | if err != nil { 93 | fmt.Println("Error converting results:", err) 94 | return 95 | } 96 | results := fp16Results.ConvertFp16() 97 | 98 | // determine the most probable classification 99 | _, maxVal, _, maxLoc := gocv.MinMaxLoc(results) 100 | fmt.Printf("description: %v, maxVal: %v\n", descriptions[maxLoc.X], maxVal) 101 | 102 | fmt.Println("Done.") 103 | } 104 | 105 | // readDescriptions reads the descriptions from a file 106 | // and returns a slice of its lines. 107 | func readDescriptions(path string) ([]string, error) { 108 | file, err := os.Open(path) 109 | if err != nil { 110 | return nil, err 111 | } 112 | defer file.Close() 113 | 114 | var lines []string 115 | scanner := bufio.NewScanner(file) 116 | for scanner.Scan() { 117 | lines = append(lines, scanner.Text()) 118 | } 119 | return lines, scanner.Err() 120 | } 121 | -------------------------------------------------------------------------------- /cmd/hello-ncs/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strconv" 7 | 8 | ncs "github.com/hybridgroup/go-ncs" 9 | ) 10 | 11 | func main() { 12 | deviceID, _ := strconv.Atoi(os.Args[1]) 13 | 14 | res, name := ncs.GetDeviceName(deviceID) 15 | if res != ncs.StatusOK { 16 | fmt.Printf("NCS Error: %v\n", res) 17 | return 18 | } 19 | 20 | fmt.Println("NCS: " + name) 21 | 22 | // open device 23 | fmt.Println("Opening NCS device " + name + "...") 24 | res, stick := ncs.OpenDevice(name) 25 | if res != ncs.StatusOK { 26 | fmt.Printf("NCS Error: %v\n", res) 27 | return 28 | } 29 | 30 | // close device 31 | fmt.Println("Closing NCS device " + name + "...") 32 | res = stick.CloseDevice() 33 | if res != ncs.StatusOK { 34 | fmt.Printf("NCS Error: %v\n", res) 35 | return 36 | } 37 | 38 | fmt.Println("Done.") 39 | } 40 | -------------------------------------------------------------------------------- /cmd/tf-video/main.go: -------------------------------------------------------------------------------- 1 | // How to use: 2 | // 3 | // This example opens a connection to a Movidius Neural Computer Stick (NCS) 4 | // then uses OpenCV to open a camera, and start displaying the current classification 5 | // of whatever the camera sees. 6 | // 7 | // You must have OpenCV/GoCV installed to use this example. 8 | // Run the following commands: 9 | // 10 | // go run ./cmd/tf-video/main.go 0 0 ~/Development/ncsdk/examples/tensorflow/inception_v3/graph ~/Development/ncsdk/examples/tensorflow/inception_v3/categories.txt 11 | // 12 | package main 13 | 14 | import ( 15 | "bufio" 16 | "fmt" 17 | "image" 18 | "image/color" 19 | "io/ioutil" 20 | "os" 21 | "strconv" 22 | 23 | ncs "github.com/hybridgroup/go-ncs" 24 | "gocv.io/x/gocv" 25 | ) 26 | 27 | func main() { 28 | deviceID, _ := strconv.Atoi(os.Args[1]) 29 | cameraID, _ := strconv.Atoi(os.Args[2]) 30 | graphFileName := os.Args[3] 31 | descriptions, _ := readDescriptions(os.Args[4]) 32 | 33 | // get name of NCS stick 34 | res, name := ncs.GetDeviceName(deviceID) 35 | if res != ncs.StatusOK { 36 | fmt.Printf("NCS Error: %v\n", res) 37 | return 38 | } 39 | 40 | // open NCS device 41 | fmt.Println("Opening NCS device " + name + "...") 42 | status, s := ncs.OpenDevice(name) 43 | if status != ncs.StatusOK { 44 | fmt.Printf("NCS Error: %v\n", status) 45 | return 46 | } 47 | defer s.CloseDevice() 48 | 49 | // load precompiled graph file in NCS format 50 | data, err := ioutil.ReadFile(graphFileName) 51 | if err != nil { 52 | fmt.Println("Error opening graph file:", err) 53 | return 54 | } 55 | 56 | // allocate graph on NCS stick 57 | fmt.Println("Allocating graph...") 58 | allocateStatus, graph := s.AllocateGraph(data) 59 | if allocateStatus != ncs.StatusOK { 60 | fmt.Printf("NCS Error: %v\n", allocateStatus) 61 | return 62 | } 63 | defer graph.DeallocateGraph() 64 | 65 | webcam, err := gocv.VideoCaptureDevice(cameraID) 66 | if err != nil { 67 | fmt.Printf("Error opening video capture device: %v\n", cameraID) 68 | return 69 | } 70 | defer webcam.Close() 71 | 72 | window := gocv.NewWindow("Movidius Tensorflow Classifier") 73 | defer window.Close() 74 | 75 | img := gocv.NewMat() 76 | defer img.Close() 77 | 78 | rgbImg := gocv.NewMat() 79 | defer rgbImg.Close() 80 | 81 | fp32Image := gocv.NewMat() 82 | defer fp32Image.Close() 83 | 84 | statusColor := color.RGBA{0, 255, 0, 0} 85 | 86 | for { 87 | if ok := webcam.Read(&img); !ok { 88 | fmt.Printf("Error cannot read device %d\n", deviceID) 89 | return 90 | } 91 | if img.Empty() { 92 | continue 93 | } 94 | 95 | // convert image to half-float blob format needed by NCS 96 | fp16data := gocv.FP16BlobFromImage(img, 1.0/128.0, image.Pt(299, 299), 128.0, true, false) 97 | 98 | // load image tensor into graph on NCS stick 99 | loadStatus := graph.LoadTensor(fp16data) 100 | if loadStatus != ncs.StatusOK { 101 | fmt.Println("Error loading tensor data:", loadStatus) 102 | return 103 | } 104 | 105 | // get result from NCS stick in fp16 format 106 | resultStatus, data := graph.GetResult() 107 | if resultStatus != ncs.StatusOK { 108 | fmt.Println("Error getting results:", resultStatus) 109 | return 110 | } 111 | 112 | // convert results from fp16 back to float32 113 | fp16Results, _ := gocv.NewMatFromBytes(1, len(data)/2, gocv.MatTypeCV16S, data) 114 | results := fp16Results.ConvertFp16() 115 | 116 | // determine the most probable classification 117 | _, maxVal, _, maxLoc := gocv.MinMaxLoc(results) 118 | 119 | // display classification 120 | if maxLoc.X != -1 { 121 | desc := descriptions[maxLoc.X+1] 122 | info := fmt.Sprintf("description: %v, maxVal: %v", desc, maxVal) 123 | gocv.PutText(&img, info, image.Pt(10, img.Rows()/2), gocv.FontHersheyPlain, 1.2, statusColor, 2) 124 | } 125 | 126 | fp16Results.Close() 127 | results.Close() 128 | 129 | window.IMShow(img) 130 | if window.WaitKey(1) >= 0 { 131 | break 132 | } 133 | } 134 | } 135 | 136 | // readDescriptions reads the descriptions from a file 137 | // and returns a slice of its lines. 138 | func readDescriptions(path string) ([]string, error) { 139 | file, err := os.Open(path) 140 | if err != nil { 141 | return nil, err 142 | } 143 | defer file.Close() 144 | 145 | var lines []string 146 | scanner := bufio.NewScanner(file) 147 | for scanner.Scan() { 148 | lines = append(lines, scanner.Text()) 149 | } 150 | return lines, scanner.Err() 151 | } 152 | -------------------------------------------------------------------------------- /go-ncs.go: -------------------------------------------------------------------------------- 1 | // Package ncs is a Go language wrapper for the Intel® Movidius™ Neural Compute Stick (NCS) 2 | // 3 | // For more information go to: 4 | // https://developer.movidius.com/ 5 | // 6 | // You must have the Intel Movidius NCS hardware in order to use this package. 7 | // 8 | package ncs 9 | -------------------------------------------------------------------------------- /ncs.cpp: -------------------------------------------------------------------------------- 1 | #include "ncs.h" 2 | #include 3 | 4 | int ncs_GetDeviceName(int idx, char* name) { 5 | mvncStatus r = mvncGetDeviceName(idx, name, NAME_SIZE); 6 | return int(r); 7 | } 8 | 9 | int ncs_OpenDevice(const char* name, void** deviceHandle) { 10 | mvncStatus r = mvncOpenDevice(name, deviceHandle); 11 | return int(r); 12 | } 13 | 14 | int ncs_CloseDevice(void* deviceHandle) { 15 | mvncStatus r = mvncCloseDevice(deviceHandle); 16 | return int(r); 17 | } 18 | 19 | int ncs_AllocateGraph(void* deviceHandle, void** graphHandle, void* graphData, unsigned int graphDataLen) { 20 | mvncStatus r = mvncAllocateGraph(deviceHandle, graphHandle, graphData, graphDataLen); 21 | return int(r); 22 | } 23 | 24 | int ncs_DeallocateGraph(void* graphHandle) { 25 | mvncStatus r = mvncDeallocateGraph(graphHandle); 26 | return int(r); 27 | } 28 | 29 | int ncs_LoadTensor(void* graphHandle, void* tensorData, unsigned int tensorDataLen) { 30 | mvncStatus r = mvncLoadTensor(graphHandle, tensorData, tensorDataLen, NULL); 31 | return int(r); 32 | } 33 | 34 | int ncs_GetResult(void* graphHandle, ResultData* resultData) { 35 | void* userParam; 36 | mvncStatus r = mvncGetResult(graphHandle, &(resultData->data), &(resultData->length), &userParam); 37 | return int(r); 38 | } 39 | -------------------------------------------------------------------------------- /ncs.go: -------------------------------------------------------------------------------- 1 | package ncs 2 | 3 | // #cgo LDFLAGS: -lmvnc 4 | /* 5 | #include 6 | */ 7 | import "C" 8 | import "unsafe" 9 | 10 | // Status is the device status 11 | type Status int 12 | 13 | const ( 14 | // StatusOK when the device is OK. 15 | StatusOK = 0 16 | 17 | // StatusBusy means device is busy, retry later. 18 | StatusBusy = -1 19 | 20 | // StatusError communicating with the device. 21 | StatusError = -2 22 | 23 | // StatusOutOfMemory means device out of memory. 24 | StatusOutOfMemory = -3 25 | 26 | // StatusDeviceNotFound means no device at the given index or name. 27 | StatusDeviceNotFound = -4 28 | 29 | // StatusInvalidParameters when at least one of the given parameters is wrong. 30 | StatusInvalidParameters = -5 31 | 32 | // StatusTimeout in the communication with the device. 33 | StatusTimeout = -6 34 | 35 | // StatusCmdNotFound means the file to boot Myriad was not found. 36 | StatusCmdNotFound = -7 37 | 38 | // StatusNoData means no data to return, call LoadTensor first. 39 | StatusNoData = -8 40 | 41 | // StatusGone means the graph or device has been closed during the operation. 42 | StatusGone = -9 43 | 44 | // StatusUnsupportedGraphFile means the graph file version is not supported. 45 | StatusUnsupportedGraphFile = -10 46 | 47 | // StatusMyriadError when an error has been reported by the device, use MVNC_DEBUG_INFO. 48 | StatusMyriadError = -11 49 | ) 50 | 51 | // Stick 52 | type Stick struct { 53 | DeviceHandle unsafe.Pointer 54 | } 55 | 56 | // Graph 57 | type Graph struct { 58 | GraphHandle unsafe.Pointer 59 | } 60 | 61 | // GetDeviceName gets the name of the NCS stick located at index. 62 | // 63 | // For more information: 64 | // https://movidius.github.io/ncsdk/c_api/mvncGetDeviceName.html 65 | // 66 | func GetDeviceName(index int) (Status, string) { 67 | buf := make([]byte, 100) 68 | ret := Status(C.ncs_GetDeviceName(C.int(index), (*C.char)(unsafe.Pointer(&buf[0])))) 69 | return ret, string(buf) 70 | } 71 | 72 | // OpenDevice initializes an NCS device and returns a Stick. 73 | // 74 | // For more information: 75 | // https://movidius.github.io/ncsdk/c_api/mvncOpenDevice.html 76 | // 77 | func OpenDevice(name string) (Status, *Stick) { 78 | cName := C.CString(name) 79 | defer C.free(unsafe.Pointer(cName)) 80 | 81 | var deviceHandle unsafe.Pointer 82 | ret := C.ncs_OpenDevice(cName, &deviceHandle) 83 | return Status(ret), &Stick{DeviceHandle: deviceHandle} 84 | } 85 | 86 | // CloseDevice closes a previously opened NCS device. 87 | // 88 | // For more information: 89 | // https://movidius.github.io/ncsdk/c_api/mvncCloseDevice.html 90 | // 91 | func (s *Stick) CloseDevice() Status { 92 | res := C.ncs_CloseDevice(s.DeviceHandle) 93 | s.DeviceHandle = nil 94 | return Status(res) 95 | } 96 | 97 | // AllocateGraph allocates a graph for use on an NCS device, and 98 | // returns a Graph. 99 | // 100 | // For more information: 101 | // https://movidius.github.io/ncsdk/c_api/mvncAllocateGraph.html 102 | // 103 | func (s *Stick) AllocateGraph(graphData []byte) (Status, *Graph) { 104 | var graphHandle unsafe.Pointer 105 | ret := Status(C.ncs_AllocateGraph(s.DeviceHandle, &graphHandle, unsafe.Pointer(&graphData[0]), C.uint(len(graphData)))) 106 | return ret, &Graph{GraphHandle: graphHandle} 107 | } 108 | 109 | // DeallocateGraph deallocates and frees resources for a Graph. 110 | // 111 | // For more information: 112 | // https://movidius.github.io/ncsdk/c_api/mvncDeallocateGraph.html 113 | // 114 | func (g *Graph) DeallocateGraph() Status { 115 | return Status(C.ncs_DeallocateGraph(g.GraphHandle)) 116 | } 117 | 118 | // LoadTensor starts inference on the NCS by providing input to the neural network. 119 | // 120 | // For more information: 121 | // https://movidius.github.io/ncsdk/c_api/mvncLoadTensor.html 122 | // 123 | func (g *Graph) LoadTensor(tensorData []byte) Status { 124 | return Status(C.ncs_LoadTensor(g.GraphHandle, unsafe.Pointer(&tensorData[0]), C.uint(len(tensorData)))) 125 | } 126 | 127 | // GetResult retrieves the result of an inference that was previously initiated 128 | // using the LoadTensor() method. 129 | // 130 | // For more information: 131 | // https://movidius.github.io/ncsdk/c_api/mvncGetResult.html 132 | // 133 | func (g *Graph) GetResult() (Status, []byte) { 134 | resultData := C.struct_ResultData{} 135 | status := C.ncs_GetResult(g.GraphHandle, &resultData) 136 | data := C.GoBytes(unsafe.Pointer(resultData.data), C.int(resultData.length)) 137 | return Status(status), data 138 | } 139 | -------------------------------------------------------------------------------- /ncs.h: -------------------------------------------------------------------------------- 1 | #ifndef _GONCS_H_ 2 | #define _GONCS_H_ 3 | 4 | #ifdef __APPLE__ 5 | #include 6 | #endif // __APPLE__ 7 | #include 8 | #include 9 | 10 | #define NAME_SIZE 100 11 | 12 | typedef struct ResultData{ 13 | void* data; 14 | uint length; 15 | } ResultData; 16 | 17 | #ifdef __cplusplus 18 | extern "C" { 19 | #endif 20 | 21 | int ncs_GetDeviceName(int idx, char* name); 22 | int ncs_OpenDevice(const char* name, void** deviceHandle); 23 | int ncs_CloseDevice(void* deviceHandle); 24 | int ncs_AllocateGraph(void* deviceHandle, void** graphHandle, void* graphData, unsigned int graphDataLen); 25 | int ncs_DeallocateGraph(void* graphHandle); 26 | int ncs_LoadTensor(void* graphHandle, void* tensorData, unsigned int tensorDataLen); 27 | int ncs_GetResult(void* graphHandle, ResultData* resultData); 28 | 29 | #ifdef __cplusplus 30 | } 31 | #endif 32 | 33 | #endif //_GONCS_H_ 34 | --------------------------------------------------------------------------------