Exemplo n.º 1
0
def analyze_img():
    #print("-------------REQUESTED ANALYZE IMAGE --------------------")
    # Set image_url to the URL of an image that you want to analyze.
    # img_url = image name
    if request.args.get('img_url'):
        image_url = app.config['IMG_FOLDER'] + request.args.get('img_url')
    else:
        return json.dumps({"Error": "Img_url is missing"})

    headers = {
        'Ocp-Apim-Subscription-Key': subscription_key_cv,
        'Content-Type': 'application/octet-stream'
    }
    params = {'visualFeatures': 'Objects'}
    image_data = open(image_url, "rb").read()
    # data = {'url': image_url}
    response = requests.post(analyze_url,
                             headers=headers,
                             params=params,
                             data=image_data)
    response.raise_for_status()

    # The 'analysis' object contains various fields that describe the image. The most
    # relevant caption for the image is obtained from the 'description' property.
    analysis = response.json()

    object_list = []
    for object in analysis['objects']:
        obj_h = object['rectangle']['h']
        desc = object['object']
        if desc in OBJECTS_HEIGHT.keys():
            real_height = OBJECTS_HEIGHT[desc.lower()]
        else:
            real_height = 15
        obj = Object(obj_h, real_height, desc, object['rectangle'])
        obj.calculate_distance()
        object_list.append(obj)
    object_list = sorted(object_list, key=lambda k: k.distance)
    response_json = []
    for obj in object_list:
        #print(str(obj))

        d = {
            'img_height': obj.img_height,
            'real_height': obj.real_height,
            'desc': obj.desc,
            'distance': obj.distance,
            'direction': get_directions(obj, image_url),
            'position': obj.position
        }
        response_json.append(d)
    #print(response_json)
    return json.dumps(response_json)