-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathms_visionapi.py
82 lines (68 loc) · 2.27 KB
/
ms_visionapi.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import http.client, urllib.parse, base64
import signal
import numpy as np
import sys
import json
headers = {
# Request headers
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': 'XXXXXXXXX',
}
params = urllib.parse.urlencode({
# Request parameters
'visualFeatures': 'Description',
})
#Saves the text to the file
def saveTextFile(text):
try:
print(text)
text_file = open("output.txt","w+")
text_file.write(text)
text_file.close()
except Exception as e:
print ("Exception occured \n")
print (e)
pass
def read_image():
pathToFileInDisk = r'Drishti.png'
with open(pathToFileInDisk, 'rb') as f:
data = f.read()
return data
def analyze_image(data):
try:
conn = http.client.HTTPSConnection('XXXXXXXX')
conn.request("POST", "/vision/XXXXXXX" % params, data, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[errno {0}] {1}".format(e.errno, e.strerror))
return data
def tag_from_data(input):
if input is not None:
# Load the original image, fetched from the URL
# data8uint = np.fromstring(input, np.uint8) # Convert string to an unsigned int array
# Get the description/tag
result = json.loads(input)
description = result['description']['captions'][0]['text']
print(data)
# img = cv2.cvtColor(cv2.imdecode(data8uint, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
# columns = defaultdict(list)
# Get image captipn and keywords
# Concatenate them to form a single string
awsstring = "I think it is "
awsstring += description
awsstring += ". And the keywords are "
num_keywords = 5
for i in range(num_keywords):
awsstring += result['description']['tags'][i]
if i != num_keywords - 1:
awsstring += ', '
return awsstring
if __name__ == '__main__':
original_sigint = signal.getsignal(signal.SIGINT)
img = read_image()
data = analyze_image(img)
text = tag_from_data(data)
saveTextFile(text)