Getting gender in the images by using Microsoft Azure

I want to use Microsoft Azure to get the gender of people in 6000 images. I use "get. analysis" for getting tags such as people, woman, man. But I need the number of people and their gender in my images. I used the command "get. analysis" for getting gender and faces but it does not work. Could anyone please help me with which command I need to use in order to get gender and faces in the images (number of women and men in the images).

import os
import numpy as np
from scipy import ndimage, misc
import sys
import requests
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
import glob
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
# Add your Computer Vision subscription key and endpoint to your environment variables.
subscription_key = 'My subscription key'
endpoint = "My endpoint key"

analyze_url = endpoint + "vision/v3.0/analyze"
img_dir = r"D:/images" # Enter Directory of all images
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
df = pd.DataFrame(columns=['PhotoID',  'Category name','Category Confidence','Tags',
                           'Caption', 'Caption Confidence', 'faces','gender'])
for i in files:
        image_data = open(i, "rb").read()
        headers = {'Ocp-Apim-Subscription-Key': subscription_key,
                   'Content-Type': 'application/octet-stream'}
        params = {'visualFeatures': 'Categories,Description,Color'}
        response =
            analyze_url, headers=headers, params=params, data=image_data)
        # 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()
        category = analysis.get('categories')
        if len(category) == 0:
            category_name = 'empty item'
            category_confidence = 'empty item'
            category = category[0]
            category_name = category.get('name')
            category_confidence = category.get('score')
        # Tags
        tag = analysis.get('description')
        tag = tag.get('tags')
        captions = analysis.get('description')
        captions = captions.get('captions')
        # faces
        faces = analysis.get ('faces')
        # gender
        gender = analysis.get ('gender')
        if len(captions) == 0:
            captions = 'empty item'
            caption = 'empty item'
            caption_confidence = 'empty item'
            captions = captions[0]
            caption= captions.get('text')
            caption_confidence = captions.get('confidence')
        #PhotoID - this has to be updated if the path changes
        i = i.strip(r'C:/image\1')
        #dominant Color
        df = df.append({'PhotoID': i,'Category name': category_name ,'Category Confidence': category_confidence, 'Tags': tag, 'Caption': caption, 'Caption Confidence': caption_confidence, 'faces': faces, 'gender': gender}, ignore_index=True)
        df2 = pd.DataFrame(df.iloc[-1, :])
        df2.T.to_csv('Image Processing.csv', mode='a', header= False)
        #image_caption = analysis["description"]["captions"][0]["text"].capitalize()
        # Display the image and overlay it with the caption.
        '''image =
        _ = plt.title(image_caption, size="x-large", y=-0.1)'''
    # Adding exception to avoid errors related to invalid photo ids
    except requests.exceptions.HTTPError:
        df = df.append({'PhotoID': 'http error','Category name': 'http error' ,'Category Confidence': 'http error' ,'Tags': 'http error', 'Caption': 'http error', 'Caption Confidence': 'http error','DominantColorForeground': 'http error','dominantColorBackground': 'http error','dominantColors': 'http error'}, ignore_index=True)
#df2 = pd.DataFrame(df.iloc[-1, :])
#df2.T.to_csv('Image Processing_sample.csv', mode='a', header=False)
df.to_excel('Image Content_sample.xlsx')

Read more here:

Content Attribution

This content was originally published by Anti at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: