-
Notifications
You must be signed in to change notification settings - Fork 22
/
MicrosoftCognitiveServicesComputerVisionTextRecognition.java
64 lines (49 loc) · 1.64 KB
/
MicrosoftCognitiveServicesComputerVisionTextRecognition.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// "input" is a string holding the path to the image file.
// "mode" is a required parameter that is set to "Printed" or "Handwritten".
public class Word {
public String text;
}
public class Line {
public int[] boundingBox;
public String text;
public Word[] words;
}
public class TextRecognitionResult {
public List<Line> lines;
}
public class TextRecognitionOperationResponse {
public String status;
public TextRecognitionResult recognitionResult;
}
Path path = Paths.get(input);
byte[] bytes = Files.readAllBytes(path);
String host = "https://westcentralus.api.cognitive.microsoft.com";
String endpoint = "/vision/v2.0/recognizeText";
String base = host.concat(endpoint);
String url = new URIBuilder(base)
.setParameter("mode", mode)
.toString();
HttpResponse<String> recognitionResponse = Unirest.post(url)
.header("Content-Type", "application/octet-stream")
.header("Ocp-Apim-Subscription-Key", subscriptionKey)
.body(bytes)
.asString();
String operationLocation = recognitionResponse
.getHeaders()
.getFirst("Operation-Location");
Gson gson = new Gson();
TextRecognitionOperationResponse operationResponse = null;
while(true) {
String operationResponseString = Unirest.get(operationLocation)
.header("Ocp-Apim-Subscription-Key", subscriptionKey)
.asString()
.getBody();
operationResponse = gson.fromJson(operationResponseString, TextRecognitionOperationResponse.class);
if (operationResponse.status.equals("Succeeded")) {
break;
}
else {
Thread.sleep(1000L);
}
}
TextRecognitionResult result = operationResponse.recognitionResult;