├── .NET ├── InferenceHosted.cs ├── InferenceLocal.cs ├── UploadHosted.cs └── UploadLocal.cs ├── .gitignore ├── Go ├── InferenceHosted.go ├── InferenceLocal.go ├── UploadHosted.go └── UploadLocal.go ├── Java ├── InferenceHosted.java ├── InferenceLocal.java ├── UploadHosted.java └── UploadLocal.java ├── Javascript ├── InferenceHosted.js ├── InferenceLocal.js ├── UploadHosted.js ├── UploadLocal.js ├── UploadLocalBySplit.js ├── package-lock.json └── package.json ├── Kotlin ├── InferenceHosted.kts ├── InferenceLocal.kts ├── UploadHosted.kts └── UploadLocal.kts ├── LICENSE ├── PHP ├── InferenceHosted.php ├── InferenceLocal.php ├── UploadHosted.php └── UploadLocal.php ├── Python ├── InferenceHosted.py ├── InferenceLocal.py ├── LuxonisOak │ ├── README.md │ ├── main.py │ └── stream_utils.py ├── UploadHosted.py ├── UploadLocal.py └── webcam │ ├── .gitignore │ ├── README.md │ ├── infer-async.py │ ├── infer-simple.py │ ├── requirements.txt │ └── roboflow_config.sample.json ├── README.md └── Ruby ├── Gemfile ├── Gemfile.lock ├── InferenceHosted.rb ├── InferenceLocal.rb ├── UploadHosted.rb └── UploadLocal.rb /.NET/InferenceHosted.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Web; 5 | 6 | namespace InferenceHosted 7 | { 8 | class InferenceHosted 9 | { 10 | static void Main(string[] args) 11 | { 12 | string API_KEY = ""; // Your API Key 13 | string imageURL = "https://i.ibb.co/jzr27x0/YOUR-IMAGE.jpg"; 14 | string MODEL_ENDPOINT = "dataset/v"; // Set model endpoint 15 | 16 | // Construct the URL 17 | string uploadURL = 18 | "https://detect.roboflow.com/" + MODEL_ENDPOINT 19 | + "?api_key=" + API_KEY 20 | + "&image=" + HttpUtility.UrlEncode(imageURL); 21 | 22 | // Service Point Config 23 | ServicePointManager.Expect100Continue = true; 24 | ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 25 | 26 | // Configure Http Request 27 | WebRequest request = WebRequest.Create(uploadURL); 28 | request.Method = "POST"; 29 | request.ContentType = "application/x-www-form-urlencoded"; 30 | request.ContentLength = 0; 31 | 32 | // Get Response 33 | string responseContent = null; 34 | using (WebResponse response = request.GetResponse()) 35 | { 36 | using (Stream stream = response.GetResponseStream()) 37 | { 38 | using (StreamReader sr99 = new StreamReader(stream)) 39 | { 40 | responseContent = sr99.ReadToEnd(); 41 | } 42 | } 43 | } 44 | 45 | Console.WriteLine(responseContent); 46 | 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.NET/InferenceLocal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Text; 5 | 6 | namespace InferenceLocal 7 | { 8 | class InferenceLocal 9 | { 10 | 11 | static void Main(string[] args) 12 | { 13 | byte[] imageArray = System.IO.File.ReadAllBytes(@"YOUR_IMAGE.jpg"); 14 | string encoded = Convert.ToBase64String(imageArray); 15 | byte[] data = Encoding.ASCII.GetBytes(encoded); 16 | string API_KEY = ""; // Your API Key 17 | string MODEL_ENDPOINT = "dataset/v"; // Set model endpoint 18 | 19 | // Construct the URL 20 | string uploadURL = 21 | "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY 22 | + "&name=YOUR_IMAGE.jpg"; 23 | 24 | // Service Request Config 25 | ServicePointManager.Expect100Continue = true; 26 | ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 27 | 28 | // Configure Request 29 | WebRequest request = WebRequest.Create(uploadURL); 30 | request.Method = "POST"; 31 | request.ContentType = "application/x-www-form-urlencoded"; 32 | request.ContentLength = data.Length; 33 | 34 | // Write Data 35 | using (Stream stream = request.GetRequestStream()) 36 | { 37 | stream.Write(data, 0, data.Length); 38 | } 39 | 40 | // Get Response 41 | string responseContent = null; 42 | using (WebResponse response = request.GetResponse()) 43 | { 44 | using (Stream stream = response.GetResponseStream()) 45 | { 46 | using (StreamReader sr99 = new StreamReader(stream)) 47 | { 48 | responseContent = sr99.ReadToEnd(); 49 | } 50 | } 51 | } 52 | 53 | Console.WriteLine(responseContent); 54 | 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /.NET/UploadHosted.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Web; 5 | 6 | namespace UploadHosted 7 | { 8 | class UploadHosted 9 | { 10 | static void Main(string[] args) 11 | { 12 | string API_KEY = ""; // Your API Key 13 | string DATASET_NAME = "your-dataset"; // Set Dataset Name (Found in Dataset URL) 14 | string imageURL = "https://i.imgur.com/PEEvqPN.png"; 15 | imageURL = HttpUtility.UrlEncode(imageURL); 16 | 17 | // Construct the URL 18 | string uploadURL = 19 | "https://api.roboflow.com/dataset/" + 20 | DATASET_NAME + "/upload" + 21 | "?api_key=" + API_KEY + 22 | "&name=YOUR_IMAGE.jpg" + 23 | "&split=train" + 24 | "&image=" + imageURL; 25 | 26 | // Service Point Config 27 | ServicePointManager.Expect100Continue = true; 28 | ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 29 | 30 | // Configure Http Request 31 | WebRequest request = WebRequest.Create(uploadURL); 32 | request.Method = "POST"; 33 | request.ContentType = "application/x-www-form-urlencoded"; 34 | request.ContentLength = 0; 35 | 36 | // Get Response 37 | string responseContent = null; 38 | using (WebResponse response = request.GetResponse()) 39 | { 40 | using (Stream stream = response.GetResponseStream()) 41 | { 42 | using (StreamReader sr99 = new StreamReader(stream)) 43 | { 44 | responseContent = sr99.ReadToEnd(); 45 | } 46 | } 47 | } 48 | 49 | Console.WriteLine(responseContent); 50 | 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /.NET/UploadLocal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Text; 5 | 6 | namespace UploadLocal 7 | { 8 | class UploadLocal 9 | { 10 | 11 | static void Main(string[] args) 12 | { 13 | byte[] imageArray = System.IO.File.ReadAllBytes(@"YOUR_IMAGE.jpg"); 14 | string encoded = Convert.ToBase64String(imageArray); 15 | byte[] data = Encoding.ASCII.GetBytes(encoded); 16 | string API_KEY = ""; // Your API Key 17 | string DATASET_NAME = "your-dataset"; // Set Dataset Name (Found in Dataset URL) 18 | 19 | // Construct the URL 20 | string uploadURL = 21 | "https://api.roboflow.com/dataset/" + 22 | DATASET_NAME + "/upload" + 23 | "?api_key=" + API_KEY + 24 | "&name=YOUR_IMAGE.jpg" + 25 | "&split=train"; 26 | 27 | // Service Request Config 28 | ServicePointManager.Expect100Continue = true; 29 | ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 30 | 31 | // Configure Request 32 | WebRequest request = WebRequest.Create(uploadURL); 33 | request.Method = "POST"; 34 | request.ContentType = "application/x-www-form-urlencoded"; 35 | request.ContentLength = data.Length; 36 | 37 | // Write Data 38 | using (Stream stream = request.GetRequestStream()) 39 | { 40 | stream.Write(data, 0, data.Length); 41 | } 42 | 43 | // Get Response 44 | string responseContent = null; 45 | using (WebResponse response = request.GetResponse()) 46 | { 47 | using (Stream stream = response.GetResponseStream()) 48 | { 49 | using (StreamReader sr99 = new StreamReader(stream)) 50 | { 51 | responseContent = sr99.ReadToEnd(); 52 | } 53 | } 54 | } 55 | 56 | Console.WriteLine(responseContent); 57 | 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ############################## 2 | ## Java 3 | ############################## 4 | .mtj.tmp/ 5 | *.class 6 | *.jar 7 | *.war 8 | *.ear 9 | *.nar 10 | hs_err_pid* 11 | *.jpg 12 | 13 | ############################## 14 | ## Maven 15 | ############################## 16 | target/ 17 | pom.xml.tag 18 | pom.xml.releaseBackup 19 | pom.xml.versionsBackup 20 | pom.xml.next 21 | pom.xml.bak 22 | release.properties 23 | dependency-reduced-pom.xml 24 | buildNumber.properties 25 | .mvn/timing.properties 26 | .mvn/wrapper/maven-wrapper.jar 27 | 28 | ############################## 29 | ## Gradle 30 | ############################## 31 | bin/ 32 | build/ 33 | .gradle 34 | .gradletasknamecache 35 | gradle-app.setting 36 | !gradle-wrapper.jar 37 | 38 | ############################## 39 | ## IntelliJ 40 | ############################## 41 | Java/out/ 42 | .idea/ 43 | .idea_modules/ 44 | *.iml 45 | *.ipr 46 | *.iws 47 | 48 | ############################## 49 | ## Eclipse 50 | ############################## 51 | .settings/ 52 | tmp/ 53 | .metadata 54 | .classpath 55 | .project 56 | *.tmp 57 | *.bak 58 | *.swp 59 | *~.nib 60 | local.properties 61 | .loadpath 62 | .factorypath 63 | 64 | ############################## 65 | ## NetBeans 66 | ############################## 67 | nbproject/private/ 68 | nbbuild/ 69 | dist/ 70 | nbdist/ 71 | nbactions.xml 72 | nb-configuration.xml 73 | 74 | ############################## 75 | ## Visual Studio Code 76 | ############################## 77 | .vscode/ 78 | .code-workspace 79 | 80 | ############################## 81 | ## OS X 82 | ############################## 83 | .DS_Store 84 | # Byte-compiled / optimized / DLL files 85 | __pycache__/ 86 | *.py[cod] 87 | *$py.class 88 | 89 | # C extensions 90 | *.so 91 | .idea 92 | 93 | # Distribution / packaging 94 | .Python 95 | develop-eggs/ 96 | downloads/ 97 | eggs/ 98 | .eggs/ 99 | lib/ 100 | lib64/ 101 | parts/ 102 | sdist/ 103 | var/ 104 | wheels/ 105 | share/python-wheels/ 106 | *.egg-info/ 107 | .installed.cfg 108 | *.egg 109 | MANIFEST 110 | 111 | # PyInstaller 112 | # Usually these files are written by a python script from a template 113 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 114 | *.manifest 115 | *.spec 116 | 117 | # Installer logs 118 | pip-log.txt 119 | pip-delete-this-directory.txt 120 | 121 | # Unit test / coverage reports 122 | htmlcov/ 123 | .tox/ 124 | .nox/ 125 | .coverage 126 | .coverage.* 127 | .cache 128 | nosetests.xml 129 | coverage.xml 130 | *.cover 131 | *.py,cover 132 | .hypothesis/ 133 | .pytest_cache/ 134 | cover/ 135 | 136 | # Translations 137 | *.mo 138 | *.pot 139 | 140 | # Django stuff: 141 | *.log 142 | local_settings.py 143 | db.sqlite3 144 | db.sqlite3-journal 145 | 146 | # Flask stuff: 147 | instance/ 148 | .webassets-cache 149 | 150 | # Scrapy stuff: 151 | .scrapy 152 | 153 | # Sphinx documentation 154 | docs/_build/ 155 | 156 | # PyBuilder 157 | .pybuilder/ 158 | 159 | # Jupyter Notebook 160 | .ipynb_checkpoints 161 | 162 | # IPython 163 | profile_default/ 164 | ipython_config.py 165 | 166 | # pyenv 167 | # For a library or package, you might want to ignore these files since the code is 168 | # intended to run in multiple environments; otherwise, check them in: 169 | # .python-version 170 | 171 | # pipenv 172 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 173 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 174 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 175 | # install all needed dependencies. 176 | #Pipfile.lock 177 | 178 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 179 | __pypackages__/ 180 | 181 | # Celery stuff 182 | celerybeat-schedule 183 | celerybeat.pid 184 | 185 | # SageMath parsed files 186 | *.sage.py 187 | 188 | # Environments 189 | .env 190 | .venv 191 | env/ 192 | Python/venv/ 193 | ENV/ 194 | env.bak/ 195 | venv.bak/ 196 | 197 | # Spyder project settings 198 | .spyderproject 199 | .spyproject 200 | 201 | # Rope project settings 202 | .ropeproject 203 | 204 | # mkdocs documentation 205 | /site 206 | 207 | # mypy 208 | .mypy_cache/ 209 | .dmypy.json 210 | dmypy.json 211 | 212 | # Pyre type checker 213 | .pyre/ 214 | 215 | # pytype static type analyzer 216 | .pytype/ 217 | 218 | # Cython debug symbols 219 | cython_debug/ 220 | 221 | node_modules/ 222 | out/ 223 | # The directory Mix will write compiled artifacts to. 224 | /_build/ 225 | 226 | # If you run "mix test --cover", coverage assets end up here. 227 | /cover/ 228 | 229 | # The directory Mix downloads your dependencies sources to. 230 | /deps/ 231 | 232 | # Where third-party dependencies like ExDoc output generated docs. 233 | /doc/ 234 | 235 | # Ignore .fetch files in case you like to edit your project deps locally. 236 | /.fetch 237 | 238 | # If the VM crashes, it generates a dump, let's ignore it too. 239 | erl_crash.dump 240 | 241 | # Also ignore archive artifacts (built via "mix archive.build"). 242 | *.ez 243 | 244 | # Ignore package tarball (built via "mix hex.build"). 245 | upload_hosted-*.tar 246 | 247 | 248 | # Temporary files for e.g. tests 249 | /tmp 250 | 251 | *.swp 252 | *.*~ 253 | project.lock.json 254 | .DS_Store 255 | *.pyc 256 | nupkg/ 257 | 258 | # Visual Studio Code 259 | .vscode 260 | 261 | # Rider 262 | .idea 263 | 264 | # User-specific files 265 | *.suo 266 | *.user 267 | *.userosscache 268 | *.sln.docstates 269 | 270 | # Build results 271 | [Dd]ebug/ 272 | [Dd]ebugPublic/ 273 | [Rr]elease/ 274 | [Rr]eleases/ 275 | x64/ 276 | x86/ 277 | build/ 278 | bld/ 279 | [Bb]in/ 280 | [Oo]bj/ 281 | [Oo]ut/ 282 | msbuild.log 283 | msbuild.err 284 | msbuild.wrn 285 | 286 | # Visual Studio 2015 287 | .vs/ 288 | 289 | .NET/*.exe 290 | .NET/*.csproj 291 | -------------------------------------------------------------------------------- /Go/InferenceHosted.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "io/ioutil" 8 | ) 9 | 10 | func main() { 11 | api_key := "" // Your API Key 12 | model_endpoint := "dataset/v" // Set model endpoint 13 | img_url := "https://i.ibb.co/jzr27x0/YOUR-IMAGE.jpg" 14 | 15 | 16 | uploadURL := "https://detect.roboflow.com/" + model_endpoint + "?api_key=" + api_key + "&image=" + url.QueryEscape(img_url) 17 | 18 | req, _ := http.NewRequest("POST", uploadURL, nil) 19 | req.Header.Set("Accept", "application/json") 20 | 21 | client := &http.Client{} 22 | resp, _ := client.Do(req) 23 | defer resp.Body.Close() 24 | 25 | bytes, _ := ioutil.ReadAll(resp.Body) 26 | fmt.Println(string(bytes)) 27 | 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Go/InferenceLocal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "encoding/base64" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "net/http" 10 | "strings" 11 | ) 12 | 13 | func main() { 14 | api_key := "" // Your API Key 15 | model_endpoint := "dataset/v" // Set model endpoint 16 | 17 | // Open file on disk. 18 | f, _ := os.Open("YOUR_IMAGE.jpg") 19 | 20 | // Read entire JPG into byte slice. 21 | reader := bufio.NewReader(f) 22 | content, _ := ioutil.ReadAll(reader) 23 | 24 | // Encode as base64. 25 | data := base64.StdEncoding.EncodeToString(content) 26 | uploadURL := "https://detect.roboflow.com/" + model_endpoint + "?api_key=" + api_key + "&name=YOUR_IMAGE.jpg" 27 | 28 | req, _ := http.NewRequest("POST", uploadURL, strings.NewReader(data)) 29 | req.Header.Set("Accept", "application/json") 30 | 31 | client := &http.Client{} 32 | resp, _ := client.Do(req) 33 | defer resp.Body.Close() 34 | 35 | bytes, _ := ioutil.ReadAll(resp.Body) 36 | fmt.Println(string(bytes)) 37 | 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Go/UploadHosted.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "io/ioutil" 8 | 9 | ) 10 | 11 | func main() { 12 | api_key := "" // Your API Key 13 | dataset_name := "Your-Dataset" // Set Dataset Name (Found in Dataset URL) 14 | img_url := "https://i.imgur.com/PEEvqPN.png" 15 | 16 | 17 | uploadURL := "https://api.roboflow.com/dataset/"+ dataset_name + "/upload"+ 18 | "?api_key=" + api_key + 19 | "&name=YOUR_IMAGE.jpg" + 20 | "&split=train" + "&image=" + url.QueryEscape(img_url) 21 | 22 | res, _ := http.Post(uploadURL, "application/x-www-form-urlencoded", nil) 23 | body, _ := ioutil.ReadAll(res.Body) 24 | fmt.Println(string(body)) 25 | 26 | 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Go/UploadLocal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "encoding/base64" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "net/http" 10 | "strings" 11 | ) 12 | 13 | func main() { 14 | api_key := "" // Your API Key 15 | dataset_name := "Your-Dataset" // Set Dataset Name (Found in Dataset URL) 16 | 17 | // Open file on disk. 18 | f, _ := os.Open("YOUR_IMAGE.jpg") 19 | 20 | // Read entire JPG into byte slice. 21 | reader := bufio.NewReader(f) 22 | content, _ := ioutil.ReadAll(reader) 23 | 24 | // Encode as base64. 25 | data := base64.StdEncoding.EncodeToString(content) 26 | uploadURL := "https://api.roboflow.com/dataset/"+ dataset_name + "/upload"+ 27 | "?api_key=" + api_key + 28 | "&name=YOUR_IMAGE.jpg" + 29 | "&split=train" 30 | 31 | res, _ := http.Post(uploadURL, "application/x-www-form-urlencoded", strings.NewReader(data)) 32 | body, _ := ioutil.ReadAll(res.Body) 33 | fmt.Println(string(body)) 34 | 35 | } -------------------------------------------------------------------------------- /Java/InferenceHosted.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.DataOutputStream; 3 | import java.io.InputStream; 4 | import java.io.InputStreamReader; 5 | import java.net.HttpURLConnection; 6 | import java.net.URL; 7 | import java.net.URLEncoder; 8 | import java.nio.charset.StandardCharsets; 9 | 10 | public class InferenceHosted { 11 | public static void main(String[] args) { 12 | String imageURL = "https://i.imgur.com/PEEvqPN.png"; // Replace Image URL 13 | String API_KEY = ""; // Your API Key 14 | String MODEL_ENDPOINT = "dataset/v"; // model endpoint 15 | 16 | // Upload URL 17 | String uploadURL = "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&image=" 18 | + URLEncoder.encode(imageURL, StandardCharsets.UTF_8); 19 | 20 | // Http Request 21 | HttpURLConnection connection = null; 22 | try { 23 | // Configure connection to URL 24 | URL url = new URL(uploadURL); 25 | connection = (HttpURLConnection) url.openConnection(); 26 | connection.setRequestMethod("POST"); 27 | connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 28 | 29 | connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.getBytes().length)); 30 | connection.setRequestProperty("Content-Language", "en-US"); 31 | connection.setUseCaches(false); 32 | connection.setDoOutput(true); 33 | 34 | // Send request 35 | DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 36 | wr.writeBytes(uploadURL); 37 | wr.close(); 38 | 39 | // Get Response 40 | InputStream stream = new URL(uploadURL).openStream(); 41 | BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 42 | String line; 43 | while ((line = reader.readLine()) != null) { 44 | System.out.println(line); 45 | } 46 | reader.close(); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } finally { 50 | if (connection != null) { 51 | connection.disconnect(); 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Java/InferenceLocal.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.net.HttpURLConnection; 3 | import java.net.URL; 4 | import java.nio.charset.StandardCharsets; 5 | import java.util.Base64; 6 | 7 | public class InferenceLocal { 8 | public static void main(String[] args) throws IOException { 9 | // Get Image Path 10 | String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg"; 11 | File file = new File(filePath); 12 | 13 | // Base 64 Encode 14 | String encodedFile; 15 | FileInputStream fileInputStreamReader = new FileInputStream(file); 16 | byte[] bytes = new byte[(int) file.length()]; 17 | fileInputStreamReader.read(bytes); 18 | encodedFile = new String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII); 19 | 20 | String API_KEY = ""; // Your API Key 21 | String MODEL_ENDPOINT = "dataset/v"; // model endpoint 22 | 23 | // Construct the URL 24 | String uploadURL = "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY 25 | + "&name=YOUR_IMAGE.jpg"; 26 | 27 | // Http Request 28 | HttpURLConnection connection = null; 29 | try { 30 | // Configure connection to URL 31 | URL url = new URL(uploadURL); 32 | connection = (HttpURLConnection) url.openConnection(); 33 | connection.setRequestMethod("POST"); 34 | connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 35 | 36 | connection.setRequestProperty("Content-Length", Integer.toString(encodedFile.getBytes().length)); 37 | connection.setRequestProperty("Content-Language", "en-US"); 38 | connection.setUseCaches(false); 39 | connection.setDoOutput(true); 40 | 41 | // Send request 42 | DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 43 | wr.writeBytes(encodedFile); 44 | wr.close(); 45 | 46 | // Get Response 47 | InputStream stream = connection.getInputStream(); 48 | BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 49 | String line; 50 | while ((line = reader.readLine()) != null) { 51 | System.out.println(line); 52 | } 53 | reader.close(); 54 | } catch (Exception e) { 55 | e.printStackTrace(); 56 | } finally { 57 | if (connection != null) { 58 | connection.disconnect(); 59 | } 60 | } 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Java/UploadHosted.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.DataOutputStream; 3 | import java.io.InputStream; 4 | import java.io.InputStreamReader; 5 | import java.net.HttpURLConnection; 6 | import java.net.URL; 7 | import java.net.URLEncoder; 8 | import java.nio.charset.StandardCharsets; 9 | 10 | public class UploadHosted { 11 | public static void main(String[] args) { 12 | String imageURL = "https://i.imgur.com/PEEvqPN.png"; // Replace Image URL 13 | String API_KEY = ""; // Your API Key 14 | String DATASET_NAME = "your-dataset"; // Set Dataset Name (Found in Dataset URL) 15 | 16 | // Upload URL 17 | String uploadURL = "https://api.roboflow.com/dataset/" + DATASET_NAME + "/upload" + "?api_key=" + API_KEY 18 | + "&name=YOUR_IMAGE.jpg" + "&split=train" + "&image=" 19 | + URLEncoder.encode(imageURL, StandardCharsets.UTF_8); 20 | 21 | // Http Request 22 | HttpURLConnection connection = null; 23 | try { 24 | // Configure connection to URL 25 | URL url = new URL(uploadURL); 26 | connection = (HttpURLConnection) url.openConnection(); 27 | connection.setRequestMethod("POST"); 28 | connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 29 | 30 | connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.getBytes().length)); 31 | connection.setRequestProperty("Content-Language", "en-US"); 32 | connection.setUseCaches(false); 33 | connection.setDoOutput(true); 34 | 35 | // Send request 36 | DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 37 | wr.writeBytes(uploadURL); 38 | wr.close(); 39 | 40 | // Get Response 41 | InputStream stream = connection.getInputStream(); 42 | BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 43 | String line; 44 | while ((line = reader.readLine()) != null) { 45 | System.out.println(line); 46 | } 47 | reader.close(); 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } finally { 51 | if (connection != null) { 52 | connection.disconnect(); 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Java/UploadLocal.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.net.HttpURLConnection; 3 | import java.net.URL; 4 | import java.nio.charset.StandardCharsets; 5 | import java.util.Base64; 6 | 7 | public class UploadLocal { 8 | public static void main(String[] args) throws IOException { 9 | // Get Image Path 10 | String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg"; 11 | File file = new File(filePath); 12 | 13 | // Base 64 Encode 14 | String encodedFile; 15 | FileInputStream fileInputStreamReader = new FileInputStream(file); 16 | byte[] bytes = new byte[(int) file.length()]; 17 | fileInputStreamReader.read(bytes); 18 | encodedFile = new String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII); 19 | 20 | String API_KEY = ""; // Your API Key 21 | String DATASET_NAME = "your-dataset"; // Set Dataset Name (Found in Dataset URL) 22 | 23 | // Construct the URL 24 | String uploadURL = 25 | "https://api.roboflow.com/dataset/"+ 26 | DATASET_NAME + "/upload" + 27 | "?api_key=" + API_KEY + 28 | "&name=YOUR_IMAGE.jpg" + 29 | "&split=train"; 30 | 31 | // Http Request 32 | HttpURLConnection connection = null; 33 | try { 34 | //Configure connection to URL 35 | URL url = new URL(uploadURL); 36 | connection = (HttpURLConnection) url.openConnection(); 37 | connection.setRequestMethod("POST"); 38 | connection.setRequestProperty("Content-Type", 39 | "application/x-www-form-urlencoded"); 40 | 41 | connection.setRequestProperty("Content-Length", 42 | Integer.toString(encodedFile.getBytes().length)); 43 | connection.setRequestProperty("Content-Language", "en-US"); 44 | connection.setUseCaches(false); 45 | connection.setDoOutput(true); 46 | 47 | //Send request 48 | DataOutputStream wr = new DataOutputStream( 49 | connection.getOutputStream()); 50 | wr.writeBytes(encodedFile); 51 | wr.close(); 52 | 53 | // Get Response 54 | InputStream stream = connection.getInputStream(); 55 | BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 56 | String line; 57 | while ((line = reader.readLine()) != null) { 58 | System.out.println(line); 59 | } 60 | reader.close(); 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | } finally { 64 | if (connection != null) { 65 | connection.disconnect(); 66 | } 67 | } 68 | 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /Javascript/InferenceHosted.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | 3 | // Model Endpoint 4 | var model_endpoint = "dataset/v"; 5 | // Enter your API Key Here 6 | var api_key = ""; 7 | 8 | axios({ 9 | method: "POST", 10 | url: "https://detect.roboflow.com/" + model_endpoint, 11 | params: { 12 | api_key: api_key, 13 | image: "https://i.imgur.com/PEEvqPN.png", 14 | }, 15 | }) 16 | .then(function (response) { 17 | console.log(response.data); 18 | }) 19 | .catch(function (error) { 20 | console.log(error.message); 21 | }); 22 | -------------------------------------------------------------------------------- /Javascript/InferenceLocal.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | const fs = require("fs"); 3 | 4 | // Model Endpoint 5 | var model_endpoint = "dataset/v"; 6 | // Enter your API Key Here 7 | var api_key = ""; 8 | 9 | const image = fs.readFileSync("YOUR_IMAGE.jpg", { 10 | encoding: "base64", 11 | }); 12 | 13 | axios({ 14 | method: "POST", 15 | url: "https://detect.roboflow.com/" + model_endpoint, 16 | params: { 17 | api_key: api_key, 18 | }, 19 | data: image, 20 | headers: { 21 | "Content-Type": "application/x-www-form-urlencoded", 22 | }, 23 | }) 24 | .then(function (response) { 25 | console.log(response.data); 26 | }) 27 | .catch(function (error) { 28 | console.log(error.message); 29 | }); 30 | -------------------------------------------------------------------------------- /Javascript/UploadHosted.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | var dataset_name = "your-dataset"; // Set Dataset Name (Found in Dataset URL) 3 | var api_key = ""; // Enter your API key here 4 | 5 | axios({ 6 | method: "POST", 7 | url: "https://api.roboflow.com/dataset/" + dataset_name + " /upload", 8 | params: { 9 | api_key: api_key, 10 | image: "https://i.imgur.com/PEEvqPN.png", 11 | name: "201-956-1246.png", 12 | split: "train", 13 | }, 14 | }) 15 | .then(function (response) { 16 | console.log(response.data); 17 | }) 18 | .catch(function (error) { 19 | console.log(error.message); 20 | }); 21 | -------------------------------------------------------------------------------- /Javascript/UploadLocal.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | const fs = require("fs"); 3 | 4 | const image = fs.readFileSync("YOUR_IMAGE.jpg", { 5 | encoding: "base64", 6 | }); 7 | 8 | var dataset_name = "your-dataset"; // Set Dataset Name (Found in Dataset URL) 9 | var api_key = ""; // Enter your API key here 10 | 11 | axios({ 12 | method: "POST", 13 | url: "https://api.roboflow.com/dataset/" + dataset_name + "/upload", 14 | params: { 15 | api_key: api_key, 16 | name: "YOUR_IMAGE.jpg", 17 | split: "train", 18 | }, 19 | data: image, 20 | headers: { 21 | "Content-Type": "application/x-www-form-urlencoded", 22 | }, 23 | }) 24 | .then(function (response) { 25 | console.log(response.data); 26 | }) 27 | .catch(function (error) { 28 | console.log(error.message); 29 | }); 30 | -------------------------------------------------------------------------------- /Javascript/UploadLocalBySplit.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const path = require('path') 3 | const axios = require('axios') 4 | const FormData = require("form-data"); 5 | 6 | const uploadLocalBySplit = ( 7 | { 8 | project_name, 9 | upload_dir, 10 | train_split = 0.7, 11 | valid_split = 0.2, 12 | api_key, 13 | } 14 | ) => { 15 | 16 | // Read from your directory of images 17 | fs.readdir(upload_dir, async function (err, files) { 18 | if (err) return console.log("Unable to scan directory: " + err); 19 | 20 | let numUploaded = 0; 21 | 22 | let split, percentUploaded; 23 | 24 | for (let i = 0; i < files.length; i ++) { 25 | // We increase numUploaded every time a file is uploaded successfully. Percentage completion is how far through the files we've gone. 26 | percentUploaded = (numUploaded / (files.length)) * 100; 27 | 28 | const imageFilePath = path.join(upload_dir, files[i]); 29 | 30 | // By default, 70% of files will be 'train', 20% will be 'valid', 10% will be test 31 | if (percentUploaded < train_split * 100) { 32 | split = "train"; // while percent uploaded is less than 70% 33 | } else if (percentUploaded < (train_split + valid_split) * 100) { 34 | split = "valid"; // while less than 90% 35 | } else { 36 | split = "test"; // final 10% 37 | } 38 | 39 | const filename = path.basename(imageFilePath); 40 | const formData = new FormData(); 41 | formData.append("name", filename); 42 | formData.append("file", fs.createReadStream(imageFilePath)); 43 | formData.append("split", split); 44 | 45 | await axios({ 46 | method: "POST", 47 | url: `https://api.roboflow.com/dataset/${project_name}/upload`, 48 | params: { 49 | api_key: api_key, 50 | }, 51 | data: formData, 52 | headers: formData.getHeaders() 53 | }) 54 | .then(function (response) { 55 | numUploaded++ 56 | console.log(response.data); 57 | }) 58 | .catch(function (error) { 59 | console.log(error.message); 60 | }); 61 | } 62 | 63 | console.log('Done') 64 | }); 65 | }; 66 | 67 | uploadLocalBySplit({ 68 | project_name: 'pull_request_test', 69 | upload_dir: '../uploads', 70 | api_key: 'PRIVATE_API_KEY' 71 | }) 72 | 73 | /* 74 | Example usage: 75 | 76 | uploadLocalBySplit({ 77 | project_name: 'pull_request_test', 78 | upload_dir: 'uploads', 79 | api_key: 'PRIVATE_API_KEY' 80 | }) 81 | 82 | Or optionally provide your own split values: 83 | 84 | uploadLocalBySplit({ 85 | project_name: 'pull_request_test', 86 | upload_dir: 'uploads', 87 | train_split: 0.6, 88 | valid_split: 0.2 89 | api_key: 'PRIVATE_API_KEY' 90 | }) 91 | */ 92 | -------------------------------------------------------------------------------- /Javascript/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "requires": true, 3 | "lockfileVersion": 1, 4 | "dependencies": { 5 | "axios": { 6 | "version": "0.21.2", 7 | "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.2.tgz", 8 | "integrity": "sha512-87otirqUw3e8CzHTMO+/9kh/FSgXt/eVDvipijwDtEuwbkySWZ9SBm6VEubmJ/kLKEoLQV/POhxXFb66bfekfg==", 9 | "requires": { 10 | "follow-redirects": "^1.14.0" 11 | } 12 | }, 13 | "follow-redirects": { 14 | "version": "1.15.2", 15 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", 16 | "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Javascript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "axios": "^0.21.2" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Kotlin/InferenceHosted.kts: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.DataOutputStream 3 | import java.io.InputStreamReader 4 | import java.net.HttpURLConnection 5 | import java.net.URL 6 | import java.net.URLEncoder 7 | 8 | fun main() { 9 | val imageURL = "https://i.imgur.com/PEEvqPN.png" // Replace Image URL 10 | val API_KEY = "" // Your API Key 11 | val MODEL_ENDPOINT = "dataset/v" // Set model endpoint 12 | 13 | // Upload URL 14 | val uploadURL = "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&image=" + URLEncoder.encode(imageURL, "utf-8"); 15 | 16 | // Http Request 17 | var connection: HttpURLConnection? = null 18 | try { 19 | // Configure connection to URL 20 | val url = URL(uploadURL) 21 | connection = url.openConnection() as HttpURLConnection 22 | connection.requestMethod = "POST" 23 | connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") 24 | connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.toByteArray().size)) 25 | connection.setRequestProperty("Content-Language", "en-US") 26 | connection.useCaches = false 27 | connection.doOutput = true 28 | 29 | // Send request 30 | val wr = DataOutputStream(connection.outputStream) 31 | wr.writeBytes(uploadURL) 32 | wr.close() 33 | 34 | // Get Response 35 | val stream = URL(uploadURL).openStream() 36 | val reader = BufferedReader(InputStreamReader(stream)) 37 | var line: String? 38 | while (reader.readLine().also { line = it } != null) { 39 | println(line) 40 | } 41 | reader.close() 42 | } catch (e: Exception) { 43 | e.printStackTrace() 44 | } finally { 45 | connection?.disconnect() 46 | } 47 | } 48 | 49 | main() -------------------------------------------------------------------------------- /Kotlin/InferenceLocal.kts: -------------------------------------------------------------------------------- 1 | import java.io.* 2 | import java.net.HttpURLConnection 3 | import java.net.URL 4 | import java.nio.charset.StandardCharsets 5 | import java.util.* 6 | 7 | fun main() { 8 | // Get Image Path 9 | val filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg" 10 | val file = File(filePath) 11 | 12 | // Base 64 Encode 13 | val encodedFile: String 14 | val fileInputStreamReader = FileInputStream(file) 15 | val bytes = ByteArray(file.length().toInt()) 16 | fileInputStreamReader.read(bytes) 17 | encodedFile = String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII) 18 | val API_KEY = "" // Your API Key 19 | val MODEL_ENDPOINT = "dataset/v" // Set model endpoint (Found in Dataset URL) 20 | 21 | // Construct the URL 22 | val uploadURL ="https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&name=YOUR_IMAGE.jpg"; 23 | 24 | // Http Request 25 | var connection: HttpURLConnection? = null 26 | try { 27 | // Configure connection to URL 28 | val url = URL(uploadURL) 29 | connection = url.openConnection() as HttpURLConnection 30 | connection.requestMethod = "POST" 31 | connection.setRequestProperty("Content-Type", 32 | "application/x-www-form-urlencoded") 33 | connection.setRequestProperty("Content-Length", 34 | Integer.toString(encodedFile.toByteArray().size)) 35 | connection.setRequestProperty("Content-Language", "en-US") 36 | connection.useCaches = false 37 | connection.doOutput = true 38 | 39 | //Send request 40 | val wr = DataOutputStream( 41 | connection.outputStream) 42 | wr.writeBytes(encodedFile) 43 | wr.close() 44 | 45 | // Get Response 46 | val stream = connection.inputStream 47 | val reader = BufferedReader(InputStreamReader(stream)) 48 | var line: String? 49 | while (reader.readLine().also { line = it } != null) { 50 | println(line) 51 | } 52 | reader.close() 53 | } catch (e: Exception) { 54 | e.printStackTrace() 55 | } finally { 56 | connection?.disconnect() 57 | } 58 | } 59 | main() -------------------------------------------------------------------------------- /Kotlin/UploadHosted.kts: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.DataOutputStream 3 | import java.io.InputStreamReader 4 | import java.net.HttpURLConnection 5 | import java.net.URL 6 | import java.net.URLEncoder 7 | import java.nio.charset.StandardCharsets 8 | 9 | fun main() { 10 | val imageURL = "https://i.imgur.com/PEEvqPN.png" // Replace Image URL 11 | val API_KEY = "" // Your API Key 12 | val DATASET_NAME = "your-dataset" // Set Dataset Name (Found in Dataset URL) 13 | 14 | // Upload URL 15 | val uploadURL = ("https://api.roboflow.com/dataset/" + DATASET_NAME + "/upload" + "?api_key=" + API_KEY 16 | + "&name=YOUR_IMAGE.jpg" + "&split=train" + "&image=" 17 | + URLEncoder.encode(imageURL, "utf-8")) 18 | 19 | // Http Request 20 | var connection: HttpURLConnection? = null 21 | try { 22 | // Configure connection to URL 23 | val url = URL(uploadURL) 24 | connection = url.openConnection() as HttpURLConnection 25 | connection.requestMethod = "POST" 26 | connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") 27 | connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.toByteArray().size)) 28 | connection.setRequestProperty("Content-Language", "en-US") 29 | connection.useCaches = false 30 | connection.doOutput = true 31 | 32 | // Send request 33 | val wr = DataOutputStream(connection.outputStream) 34 | wr.writeBytes(uploadURL) 35 | wr.close() 36 | 37 | // Get Response 38 | val stream = connection.inputStream 39 | val reader = BufferedReader(InputStreamReader(stream)) 40 | var line: String? 41 | while (reader.readLine().also { line = it } != null) { 42 | println(line) 43 | } 44 | reader.close() 45 | } catch (e: Exception) { 46 | e.printStackTrace() 47 | } finally { 48 | connection?.disconnect() 49 | } 50 | } 51 | 52 | main() -------------------------------------------------------------------------------- /Kotlin/UploadLocal.kts: -------------------------------------------------------------------------------- 1 | import java.io.* 2 | import java.net.HttpURLConnection 3 | import java.net.URL 4 | import java.nio.charset.StandardCharsets 5 | import java.util.* 6 | 7 | fun main() { 8 | // Get Image Path 9 | val filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg" 10 | val file = File(filePath) 11 | 12 | // Base 64 Encode 13 | val encodedFile: String 14 | val fileInputStreamReader = FileInputStream(file) 15 | val bytes = ByteArray(file.length().toInt()) 16 | fileInputStreamReader.read(bytes) 17 | encodedFile = String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII) 18 | val API_KEY = "" // Your API Key 19 | val DATASET_NAME = "your-dataset" // Set Dataset Name (Found in Dataset URL) 20 | 21 | // Construct the URL 22 | val uploadURL = "https://api.roboflow.com/dataset/" + 23 | DATASET_NAME + "/upload" + 24 | "?api_key=" + API_KEY + 25 | "&name=YOUR_IMAGE.jpg" + 26 | "&split=train" 27 | 28 | // Http Request 29 | var connection: HttpURLConnection? = null 30 | try { 31 | // Configure connection to URL 32 | val url = URL(uploadURL) 33 | connection = url.openConnection() as HttpURLConnection 34 | connection.requestMethod = "POST" 35 | connection.setRequestProperty("Content-Type", 36 | "application/x-www-form-urlencoded") 37 | connection.setRequestProperty("Content-Length", 38 | Integer.toString(encodedFile.toByteArray().size)) 39 | connection.setRequestProperty("Content-Language", "en-US") 40 | connection.useCaches = false 41 | connection.doOutput = true 42 | 43 | //Send request 44 | val wr = DataOutputStream( 45 | connection.outputStream) 46 | wr.writeBytes(encodedFile) 47 | wr.close() 48 | 49 | // Get Response 50 | val stream = connection.inputStream 51 | val reader = BufferedReader(InputStreamReader(stream)) 52 | var line: String? 53 | while (reader.readLine().also { line = it } != null) { 54 | println(line) 55 | } 56 | reader.close() 57 | } catch (e: Exception) { 58 | e.printStackTrace() 59 | } finally { 60 | connection?.disconnect() 61 | } 62 | } 63 | main() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 Roboflow 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PHP/InferenceHosted.php: -------------------------------------------------------------------------------- 1 | array ( 15 | 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 16 | 'method' => 'POST' 17 | )); 18 | 19 | $context = stream_context_create($options); 20 | $result = file_get_contents($url, false, $context); 21 | echo $result; 22 | ?> -------------------------------------------------------------------------------- /PHP/InferenceLocal.php: -------------------------------------------------------------------------------- 1 | array ( 17 | 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 18 | 'method' => 'POST', 19 | 'content' => $data 20 | )); 21 | 22 | $context = stream_context_create($options); 23 | $result = file_get_contents($url, false, $context); 24 | echo $result; 25 | ?> -------------------------------------------------------------------------------- /PHP/UploadHosted.php: -------------------------------------------------------------------------------- 1 | array ( 18 | 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 19 | 'method' => 'POST' 20 | )); 21 | 22 | $context = stream_context_create($options); 23 | $result = file_get_contents($url, false, $context); 24 | echo $result; 25 | ?> -------------------------------------------------------------------------------- /PHP/UploadLocal.php: -------------------------------------------------------------------------------- 1 | array ( 19 | 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 20 | 'method' => 'POST', 21 | 'content' => $data 22 | )); 23 | 24 | $context = stream_context_create($options); 25 | $result = file_get_contents($url, false, $context); 26 | echo $result; 27 | ?> -------------------------------------------------------------------------------- /Python/InferenceHosted.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import urllib.parse 3 | 4 | # Your API Key 5 | api_key = "" 6 | 7 | # Model Endpoint 8 | model_endpoint = "dataset/v" 9 | 10 | # Construct the URL 11 | img_url = "https://i.imgur.com/PEEvqPN.png" 12 | upload_url = "".join([ 13 | "https://detect.roboflow.com/" + model_endpoint, 14 | "?api_key=" + api_key, 15 | "&image=" + urllib.parse.quote_plus(img_url) 16 | ]) 17 | 18 | # POST to the API 19 | r = requests.post(upload_url) 20 | 21 | # Output result 22 | print(r.json()) -------------------------------------------------------------------------------- /Python/InferenceLocal.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import base64 3 | import io 4 | from PIL import Image 5 | 6 | # Load Image with PIL 7 | image = Image.open("YOUR_IMAGE.jpg").convert("RGB") 8 | 9 | # Convert to JPEG Buffer 10 | buffered = io.BytesIO() 11 | image.save(buffered, quality=90, format="JPEG") 12 | 13 | # Base 64 Encode 14 | img_str = base64.b64encode(buffered.getvalue()) 15 | img_str = img_str.decode("ascii") 16 | 17 | # Your API Key 18 | api_key = "" 19 | 20 | # Model Endpoint 21 | model_endpoint = "dataset/v" 22 | 23 | # Construct the URL 24 | upload_url = "".join([ 25 | "https://detect.roboflow.com/" + model_endpoint, 26 | "?api_key=" + api_key, 27 | "&name=YOUR_IMAGE.jpg" 28 | ]) 29 | 30 | # POST to the API 31 | r = requests.post(upload_url, data=img_str, headers={ 32 | "Content-Type": "application/x-www-form-urlencoded" 33 | }) 34 | 35 | # Output result 36 | print(r.json()) -------------------------------------------------------------------------------- /Python/LuxonisOak/README.md: -------------------------------------------------------------------------------- 1 | ## Luxonis OAK with MJPEG Streaming Example 2 | 3 | This script demonstrates how to incorporate MJPEG streaming into a Roboflow + Luxonis OAK system. This is 4 | especially useful when the host is headless (no external display). In this case, the detection visualization 5 | can conveniently be accessed over a local network. 6 | 7 | If indeed run on a headless host, ensure that cv2.imshow calls are removed (the script will crash since there 8 | is no display). 9 | -------------------------------------------------------------------------------- /Python/LuxonisOak/main.py: -------------------------------------------------------------------------------- 1 | from roboflowoak import RoboflowOak 2 | import cv2 3 | import time 4 | import numpy as np 5 | 6 | from stream_utils import MakeStreamingHandler, StreamingOutput, StreamingServer 7 | 8 | if __name__ == '__main__': 9 | # instantiating an object (rf) with the RoboflowOak module 10 | rf = RoboflowOak(model="[MODEL]", confidence=0.05, overlap=0.5, 11 | version="[VERSION]", api_key="[API_KEY]", rgb=True, 12 | depth=True, device=None, blocking=True) 13 | 14 | # Create our MPEG streaming server 15 | # The stream will be available at http://localhost:8000/stream.mjpg by default 16 | output = StreamingOutput() 17 | address = ('', 8000) # Change 8000 to the port you want to serve the MPJEG stream on 18 | StreamingHandler = MakeStreamingHandler(output) 19 | server = StreamingServer(address, StreamingHandler) 20 | server.serve_forever() 21 | 22 | # Running our model and displaying the video output with detections 23 | while True: 24 | t0 = time.time() 25 | # The rf.detect() function runs the model inference 26 | result, frame, raw_frame, depth = rf.detect(visualize=True) 27 | predictions = result["predictions"] 28 | #{ 29 | # predictions: 30 | # [ { 31 | # x: (middle), 32 | # y:(middle), 33 | # width: 34 | # height: 35 | # depth: ###-> 36 | # confidence: 37 | # class: 38 | # mask: { 39 | # ] 40 | #} 41 | #frame - frame after preprocs, with predictions 42 | #raw_frame - original frame from your OAK 43 | #depth - depth map for raw_frame, center-rectified to the center camera 44 | 45 | # timing: for benchmarking purposes 46 | t = time.time()-t0 47 | print("FPS ", 1/t) 48 | print("PREDICTIONS ", [p.json() for p in predictions]) 49 | 50 | # Uncomment the follow two lines to enable 51 | # the optional depth view 52 | # max_depth = np.amax(depth) 53 | # cv2.imshow("depth", depth/max_depth) 54 | 55 | # displaying the video feed as successive frames 56 | cv2.imshow("frame", frame) 57 | 58 | # pass the latest frame to the MJPEG stream 59 | output.write(cv2.imencode('.JPEG', frame)[1].tobytes()) 60 | 61 | # how to close the OAK inference window / stop inference: CTRL+q or CTRL+c 62 | if cv2.waitKey(1) == ord('q'): 63 | break 64 | 65 | -------------------------------------------------------------------------------- /Python/LuxonisOak/stream_utils.py: -------------------------------------------------------------------------------- 1 | 2 | import io 3 | import logging 4 | import socketserver 5 | from threading import Condition, Thread 6 | from http import server 7 | 8 | class StreamingOutput(object): 9 | def __init__(self): 10 | self.frame = None 11 | self.buffer = io.BytesIO() 12 | self.condition = Condition() 13 | 14 | def write(self, buf): 15 | if buf.startswith(b'\xff\xd8'): 16 | print(True) 17 | # New frame, copy the existing buffer's content and notify all 18 | # clients it's available 19 | self.buffer.truncate() 20 | with self.condition: 21 | self.frame = self.buffer.getvalue() 22 | self.condition.notify_all() 23 | self.buffer.seek(0) 24 | return self.buffer.write(buf) 25 | 26 | def MakeStreamingHandler(output): 27 | class StreamingHandler(server.BaseHTTPRequestHandler): 28 | def __init__(self, *args, **kwargs): 29 | super(StreamingHandler, self).__init__(*args, **kwargs) 30 | self.output = output 31 | 32 | page = PAGE="""\ 33 | 34 | 35 | roboflowoak Stream View 36 | 37 | 38 |
39 | 40 | 41 | """ 42 | content = page.encode('utf-8') 43 | 44 | def do_GET(self): 45 | if self.path == '/': 46 | self.send_response(301) 47 | self.send_header('Location', '/index.html') 48 | self.end_headers() 49 | elif self.path == '/index.html': 50 | self.send_response(200) 51 | self.send_header('Content-Type', 'text/html') 52 | self.send_header('Content-Length', len(self.content)) 53 | self.end_headers() 54 | self.wfile.write(self.content) 55 | elif self.path == '/stream.mjpg': 56 | self.send_response(200) 57 | self.send_header('Age', 0) 58 | self.send_header('Cache-Control', 'no-cache, private') 59 | self.send_header('Pragma', 'no-cache') 60 | self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME') 61 | self.end_headers() 62 | try: 63 | while True: 64 | with output.condition: 65 | output.condition.wait() 66 | frame = output.frame 67 | self.wfile.write(b'--FRAME\r\n') 68 | self.send_header('Content-Type', 'image/jpeg') 69 | self.send_header('Content-Length', len(frame)) 70 | self.end_headers() 71 | self.wfile.write(frame) 72 | self.wfile.write(b'\r\n') 73 | except Exception as e: 74 | logging.warning( 75 | 'Removed streaming client %s: %s', 76 | self.client_address, str(e)) 77 | else: 78 | self.send_error(404) 79 | self.end_headers() 80 | 81 | return StreamingHandler 82 | 83 | class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): 84 | allow_reuse_address = True 85 | daemon_threads = True 86 | 87 | def serve_forever(self, *k, **kw) -> None: 88 | Thread(target=super().serve_forever, args=k, kwargs=kw).start() 89 | -------------------------------------------------------------------------------- /Python/UploadHosted.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import urllib.parse 3 | 4 | # Construct the URL 5 | img_url = "https://i.imgur.com/PEEvqPN.png" 6 | # Your API Key 7 | api_key = "" 8 | # Set Dataset Name (Found in Dataset URL) 9 | dataset_name = "your-dataset" 10 | 11 | upload_url = "".join([ 12 | "https://api.roboflow.com/dataset/" + dataset_name + "/upload", 13 | "?api_key=" + api_key, 14 | "&name=201-956-1246.png", 15 | "&split=train", 16 | "&image=" + urllib.parse.quote_plus(img_url) 17 | ]) 18 | 19 | # POST to the API 20 | r = requests.post(upload_url) 21 | 22 | # # Output result 23 | print(r.json()) -------------------------------------------------------------------------------- /Python/UploadLocal.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import base64 3 | import io 4 | from PIL import Image 5 | 6 | # Load Image with PIL 7 | image = Image.open("YOUR_IMAGE.jpg").convert("RGB") 8 | 9 | # Convert to JPEG Buffer 10 | buffered = io.BytesIO() 11 | image.save(buffered, quality=90, format="JPEG") 12 | 13 | # Base 64 Encode 14 | img_str = base64.b64encode(buffered.getvalue()) 15 | img_str = img_str.decode("ascii") 16 | 17 | # Your API Key 18 | api_key = "" 19 | # Set Dataset Name (Found in Dataset URL) 20 | dataset_name = "your-dataset" 21 | 22 | # Construct the URL 23 | upload_url = "".join([ 24 | "https://api.roboflow.com/dataset/"+ dataset_name + "/upload", 25 | "?api_key=" + api_key, 26 | "&name=YOUR_IMAGE.jpg", 27 | "&split=train" 28 | ]) 29 | 30 | # POST to the API 31 | r = requests.post(upload_url, data=img_str, headers={ 32 | "Content-Type": "application/x-www-form-urlencoded" 33 | }) 34 | 35 | # Output result 36 | print(r) -------------------------------------------------------------------------------- /Python/webcam/.gitignore: -------------------------------------------------------------------------------- 1 | env 2 | roboflow_config.json 3 | -------------------------------------------------------------------------------- /Python/webcam/README.md: -------------------------------------------------------------------------------- 1 | # Python Webcam Inference Examples 2 | These scripts demonstrate how to use the Roboflow Infer API to get predictions 3 | from a live webcam feed. 4 | 5 | ![python-webcam](https://user-images.githubusercontent.com/870796/112769782-7d29ad00-8fe8-11eb-8233-2e1b81781dd6.gif) 6 | 7 | ## Installation 8 | Install the requirements with pip3 ([`infer-async.py`](infer-async.py) requires 9 | Python 3.7+ for [asyncio](https://docs.python.org/3/library/asyncio.html) support.) 10 | ``` 11 | pip install -r requirements.txt 12 | ``` 13 | 14 | ## Configuration 15 | Create a `roboflow_config.json` file with your Roboflow API key, model name, and 16 | model size (defaults to 416 if you didn't use a `resize` preprocessing step 17 | when you created your Version in Roboflow). 18 | 19 | ## Usage 20 | 21 | **[`infer-simple.py`](infer-simple.py)** does inference sequentially; meaning it 22 | waits for the predictions from the previous frame before sending another. 23 | The framerate depends on the latency between your machine and the Inference API. 24 | 25 | In our tests, we saw ~4 fps with the Roboflow 26 | [Hosted API](https://docs.roboflow.com/inference/hosted-api) 27 | and ~8 fps with an NVIDIA Jetson Xavier NX running the 28 | [on-prem Roboflow Infer API](https://docs.roboflow.com/inference/nvidia-jetson). 29 | 30 | **[`infer-async.py`](infer-async.py)** does inference in parallel using a frame 31 | buffer which you can configure in your `roboflow_config.json`. You should be able 32 | to achieve arbitrary framerates by adjusting the buffer size. 33 | -------------------------------------------------------------------------------- /Python/webcam/infer-async.py: -------------------------------------------------------------------------------- 1 | # load config 2 | import json 3 | with open('roboflow_config.json') as f: 4 | config = json.load(f) 5 | 6 | ROBOFLOW_API_KEY = config["ROBOFLOW_API_KEY"] 7 | ROBOFLOW_MODEL = config["ROBOFLOW_MODEL"] 8 | ROBOFLOW_SIZE = config["ROBOFLOW_SIZE"] 9 | 10 | FRAMERATE = config["FRAMERATE"] 11 | BUFFER = config["BUFFER"] 12 | 13 | import asyncio 14 | import cv2 15 | import base64 16 | import numpy as np 17 | import httpx 18 | import time 19 | 20 | # Construct the Roboflow Infer URL 21 | # (if running locally replace https://detect.roboflow.com/ with eg http://127.0.0.1:9001/) 22 | upload_url = "".join([ 23 | "https://detect.roboflow.com/", 24 | ROBOFLOW_MODEL, 25 | "?api_key=", 26 | ROBOFLOW_API_KEY, 27 | "&format=image", # Change to json if you want the prediction boxes, not the visualization 28 | "&stroke=5" 29 | ]) 30 | 31 | # Get webcam interface via opencv-python 32 | video = cv2.VideoCapture(0) 33 | 34 | # Infer via the Roboflow Infer API and return the result 35 | # Takes an httpx.AsyncClient as a parameter 36 | async def infer(requests): 37 | # Get the current image from the webcam 38 | ret, img = video.read() 39 | 40 | # Resize (while maintaining the aspect ratio) to improve speed and save bandwidth 41 | height, width, channels = img.shape 42 | scale = ROBOFLOW_SIZE / max(height, width) 43 | img = cv2.resize(img, (round(scale * width), round(scale * height))) 44 | 45 | # Encode image to base64 string 46 | retval, buffer = cv2.imencode('.jpg', img) 47 | img_str = base64.b64encode(buffer) 48 | 49 | # Get prediction from Roboflow Infer API 50 | resp = await requests.post(upload_url, data=img_str, headers={ 51 | "Content-Type": "application/x-www-form-urlencoded" 52 | }) 53 | 54 | # Parse result image 55 | image = np.asarray(bytearray(resp.content), dtype="uint8") 56 | image = cv2.imdecode(image, cv2.IMREAD_COLOR) 57 | 58 | return image 59 | 60 | # Main loop; infers at FRAMERATE frames per second until you press "q" 61 | async def main(): 62 | # Initialize 63 | last_frame = time.time() 64 | 65 | # Initialize a buffer of images 66 | futures = [] 67 | 68 | async with httpx.AsyncClient() as requests: 69 | while 1: 70 | # On "q" keypress, exit 71 | if(cv2.waitKey(1) == ord('q')): 72 | break 73 | 74 | # Throttle to FRAMERATE fps and print actual frames per second achieved 75 | elapsed = time.time() - last_frame 76 | await asyncio.sleep(max(0, 1/FRAMERATE - elapsed)) 77 | print((1/(time.time()-last_frame)), " fps") 78 | last_frame = time.time() 79 | 80 | # Enqueue the inference request and safe it to our buffer 81 | task = asyncio.create_task(infer(requests)) 82 | futures.append(task) 83 | 84 | # Wait until our buffer is big enough before we start displaying results 85 | if len(futures) < BUFFER * FRAMERATE: 86 | continue 87 | 88 | # Remove the first image from our buffer 89 | # wait for it to finish loading (if necessary) 90 | image = await futures.pop(0) 91 | # And display the inference results 92 | cv2.imshow('image', image) 93 | 94 | # Run our main loop 95 | asyncio.run(main()) 96 | 97 | # Release resources when finished 98 | video.release() 99 | cv2.destroyAllWindows() 100 | -------------------------------------------------------------------------------- /Python/webcam/infer-simple.py: -------------------------------------------------------------------------------- 1 | # load config 2 | import json 3 | with open('roboflow_config.json') as f: 4 | config = json.load(f) 5 | 6 | ROBOFLOW_API_KEY = config["ROBOFLOW_API_KEY"] 7 | ROBOFLOW_MODEL = config["ROBOFLOW_MODEL"] 8 | ROBOFLOW_SIZE = config["ROBOFLOW_SIZE"] 9 | 10 | FRAMERATE = config["FRAMERATE"] 11 | BUFFER = config["BUFFER"] 12 | 13 | import cv2 14 | import base64 15 | import numpy as np 16 | import requests 17 | import time 18 | 19 | # Construct the Roboflow Infer URL 20 | # (if running locally replace https://detect.roboflow.com/ with eg http://127.0.0.1:9001/) 21 | upload_url = "".join([ 22 | "https://detect.roboflow.com/", 23 | ROBOFLOW_MODEL, 24 | "?api_key=", 25 | ROBOFLOW_API_KEY, 26 | "&format=image", 27 | "&stroke=5" 28 | ]) 29 | 30 | # Get webcam interface via opencv-python 31 | video = cv2.VideoCapture(0) 32 | 33 | # Infer via the Roboflow Infer API and return the result 34 | def infer(): 35 | # Get the current image from the webcam 36 | ret, img = video.read() 37 | 38 | # Resize (while maintaining the aspect ratio) to improve speed and save bandwidth 39 | height, width, channels = img.shape 40 | scale = ROBOFLOW_SIZE / max(height, width) 41 | img = cv2.resize(img, (round(scale * width), round(scale * height))) 42 | 43 | # Encode image to base64 string 44 | retval, buffer = cv2.imencode('.jpg', img) 45 | img_str = base64.b64encode(buffer) 46 | 47 | # Get prediction from Roboflow Infer API 48 | resp = requests.post(upload_url, data=img_str, headers={ 49 | "Content-Type": "application/x-www-form-urlencoded" 50 | }, stream=True).raw 51 | 52 | # Parse result image 53 | image = np.asarray(bytearray(resp.read()), dtype="uint8") 54 | image = cv2.imdecode(image, cv2.IMREAD_COLOR) 55 | 56 | return image 57 | 58 | # Main loop; infers sequentially until you press "q" 59 | while 1: 60 | # On "q" keypress, exit 61 | if(cv2.waitKey(1) == ord('q')): 62 | break 63 | 64 | # Capture start time to calculate fps 65 | start = time.time() 66 | 67 | # Synchronously get a prediction from the Roboflow Infer API 68 | image = infer() 69 | # And display the inference results 70 | cv2.imshow('image', image) 71 | 72 | # Print frames per second 73 | print((1/(time.time()-start)), " fps") 74 | 75 | # Release resources when finished 76 | video.release() 77 | cv2.destroyAllWindows() 78 | -------------------------------------------------------------------------------- /Python/webcam/requirements.txt: -------------------------------------------------------------------------------- 1 | asyncio 2 | httpx 3 | numpy 4 | opencv-python 5 | requests 6 | -------------------------------------------------------------------------------- /Python/webcam/roboflow_config.sample.json: -------------------------------------------------------------------------------- 1 | { 2 | "__comment1": "Obtain these values via Roboflow", 3 | "ROBOFLOW_API_KEY": "xxxxxxxxxx", 4 | "ROBOFLOW_MODEL": "xx-name--#", 5 | "ROBOFLOW_SIZE": 416, 6 | 7 | "__comment2": "The following are only needed for infer-async.py", 8 | "FRAMERATE": 24, 9 | "BUFFER": 0.5 10 | } 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Roboflow API Snippets 2 | 3 | Repository for versioning snippets that show how to use Roboflow APIs in different languages. 4 | 5 | ## API Snippets Progress 6 | 7 | ### Completed 8 | 9 | ###### Upload APIs 10 | 11 | - Kotlin (Local and Hosted) 12 | - Go (Local and Hosted) 13 | - .NET (Local and Hosted) 14 | - PHP (Local and Hosted) 15 | - Ruby (Local and Hosted) 16 | - Python (Local and Hosted) 17 | - Java (Local and Hosted) 18 | - Javascript (Local and Hosted) 19 | 20 | ###### Inference APIs 21 | 22 | - Python (Local and Hosted) 23 | - Javascript (Local and Hosted) 24 | - Java (Local and Hosted) 25 | - Kotlin (Local and Hosted) 26 | - Ruby (Local and Hosted) 27 | - Go (Local and Hosted) 28 | - PHP (Local and Hosted) 29 | - .NET (Local and Hosted) 30 | 31 | ### In-Progress 32 | 33 | ###### Upload APIs 34 | 35 | - None 36 | 37 | ###### Inference APIs 38 | 39 | - None 40 | 41 | ### Not Started 42 | 43 | ###### Upload APIs 44 | 45 | - Elixir (Local and Hosted) 46 | - Swift (Local and Hosted) 47 | - Objective C (Local and Hosted) 48 | 49 | ###### Inference APIs 50 | 51 | - Elixir (Local and Hosted) 52 | - Swift (Local and Hosted) 53 | - Objective C (Local and Hosted) 54 | -------------------------------------------------------------------------------- /Ruby/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "httparty", "~> 0.18.1" 4 | gem "base64", "~> 0.1.0" 5 | gem "cgi", "~> 0.2.2" 6 | -------------------------------------------------------------------------------- /Ruby/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | base64 (0.1.0) 5 | cgi (0.2.2) 6 | httparty (0.18.1) 7 | mime-types (~> 3.0) 8 | multi_xml (>= 0.5.2) 9 | mime-types (3.3.1) 10 | mime-types-data (~> 3.2015) 11 | mime-types-data (3.2021.0225) 12 | multi_xml (0.6.0) 13 | 14 | PLATFORMS 15 | x64-mingw32 16 | x86_64-linux 17 | 18 | DEPENDENCIES 19 | base64 (~> 0.1.0) 20 | cgi (~> 0.2.2) 21 | httparty (~> 0.18.1) 22 | 23 | BUNDLED WITH 24 | 2.2.15 25 | -------------------------------------------------------------------------------- /Ruby/InferenceHosted.rb: -------------------------------------------------------------------------------- 1 | require 'httparty' 2 | require 'cgi' 3 | 4 | model_endpoint = "dataset/v" # Set model endpoint 5 | api_key = "" # Your API KEY Here 6 | img_url = "https://i.imgur.com/PEEvqPN.png" # Construct the URL 7 | 8 | img_url = CGI::escape(img_url) 9 | 10 | params = "?api_key=" + api_key + "&image=" + img_url 11 | 12 | response = HTTParty.post( 13 | "https://detect.roboflow.com/" + model_endpoint + params, 14 | headers: { 15 | 'Content-Type' => 'application/x-www-form-urlencoded', 16 | 'charset' => 'utf-8' 17 | }) 18 | 19 | puts response -------------------------------------------------------------------------------- /Ruby/InferenceLocal.rb: -------------------------------------------------------------------------------- 1 | require 'base64' 2 | require 'httparty' 3 | 4 | encoded = Base64.encode64(File.open("YOUR_IMAGE.jpg", "rb").read) 5 | model_endpoint = "dataset/v" # Set model endpoint 6 | api_key = "" # Your API KEY Here 7 | 8 | params = "?api_key=" + api_key 9 | + "&name=YOUR_IMAGE.jpg" 10 | 11 | response = HTTParty.post( 12 | "https://detect.roboflow.com/" + model_endpoint + params, 13 | body: encoded, 14 | headers: { 15 | 'Content-Type' => 'application/x-www-form-urlencoded', 16 | 'charset' => 'utf-8' 17 | }) 18 | 19 | puts response 20 | 21 | -------------------------------------------------------------------------------- /Ruby/UploadHosted.rb: -------------------------------------------------------------------------------- 1 | require 'httparty' 2 | require 'cgi' 3 | 4 | dataset_name = "your-dataset" # Set Dataset Name (Found in Dataset URL) 5 | api_key = "" # Your API KEY Here 6 | img_url = "https://i.imgur.com/PEEvqPN.png" # Construct the URL 7 | 8 | img_url = CGI::escape(img_url) 9 | 10 | params = "?api_key=" + api_key + 11 | "&name=YOUR_IMAGE.jpg" + 12 | "&split=train" + 13 | "&image=" + img_url 14 | 15 | response = HTTParty.post( 16 | "https://api.roboflow.com/dataset/" + dataset_name + "/upload" + params, 17 | headers: { 18 | 'Content-Type' => 'application/x-www-form-urlencoded', 19 | 'charset' => 'utf-8' 20 | }) 21 | 22 | puts response -------------------------------------------------------------------------------- /Ruby/UploadLocal.rb: -------------------------------------------------------------------------------- 1 | require 'base64' 2 | require 'httparty' 3 | 4 | encoded = Base64.encode64(File.open("YOUR_IMAGE.jpg", "rb").read) 5 | dataset_name = "your-dataset" # Set Dataset Name (Found in Dataset URL) 6 | api_key = "" # Your API KEY Here 7 | 8 | params = "?api_key=" + api_key + 9 | "&name=YOUR_IMAGE.jpg" + 10 | "&split=train" 11 | 12 | response = HTTParty.post( 13 | "https://api.roboflow.com/dataset/" + dataset_name + "/upload" + params, 14 | body: encoded, 15 | headers: { 16 | 'Content-Type' => 'application/x-www-form-urlencoded', 17 | 'charset' => 'utf-8' 18 | }) 19 | 20 | puts response 21 | 22 | --------------------------------------------------------------------------------