Guest User

Untitled

a guest
Mar 8th, 2021
790
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. """Download training photos from Azure Custom Vision workspace
  4. """
  5.  
  6. # reference: ajakupov@expertime.com
  7.  
  8. import http.client
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import base64
  13. import json
  14. import os
  15. import cv2
  16. import numpy as np
  17.  
  18. # create tag folders if they do not exist
  19. tag_folders = ['desiccation']
  20. for folder in tag_folders:
  21.     if not os.path.exists(folder):
  22.         os.makedirs(folder)
  23.  
  24. try:
  25.  # base url
  26.     conn = http.client.HTTPSConnection(
  27.  'australiaeast.api.cognitive.microsoft.com')
  28.     headers = {"Training-key": "{training key}"}
  29.     conn.request(
  30.  "GET", "/customvision/v3.3/Training/projects/{Project id}/images/tagged?take=256&skip=0",headers = headers)
  31.     response = conn.getresponse()
  32.    
  33.     encoding = 'utf-8'
  34.  # get response as a raw string
  35.     data = response.read().decode(encoding)
  36.  # convert the string to a json object
  37.     data_json = json.loads(data)
  38.    
  39.     conn.close()
  40.    
  41.     # write json to file
  42.     with open('data.json', 'a') as f:
  43.         json.dump(data, f, ensure_ascii=False, indent=4)
  44.    
  45.     for item in data_json:
  46.         # uri for image download
  47.         originalImageUri = item['originalImageUri']
  48.         # image tag
  49.         tag_name = item["tags"][0]["tagName"]
  50.         #create the object, assign it to a variable
  51.         proxy = urllib.request.ProxyHandler({'http': '127.0.0.1'})
  52.         # construct a new opener using your proxy settings
  53.         opener = urllib.request.build_opener(proxy)
  54.         # install the openen on the module-level
  55.         urllib.request.install_opener(opener)
  56.         # download image from uri
  57.         output_file = os.path.join(tag_name, str(item["id"]) + '.jpg')
  58.         urllib.request.urlretrieve(originalImageUri, output_file)
  59.         image_cv = cv2.imread(output_file)
  60.         HEIGHT, WIDTH, channels = image_cv.shape
  61.         for region in item["regions"]:
  62.             x1, y1 = region.get('left'), region.get('top')
  63.             x2, y2 = x1 + region.get('width'), y1 + region.get('height'),
  64.             x1, y1, x2, y2 = round(x1 * WIDTH), round(y1 * HEIGHT), round(x2 * WIDTH), round(y2 * HEIGHT)
  65.             image_cv = cv2.rectangle(image_cv, (x1, y1), (x2, y2), (0, 0, 0), 3)
  66.        
  67.         cv2.imwrite(output_file, image_cv)
  68.        
  69. except Exception as e:
  70.     print(e)
  71.  
  72.  
Add Comment
Please, Sign In to add comment