在图像上绘制文字

时间:2018-09-13 07:59:24

标签: python image python-imaging-library

我是OpenCV的初学者,使用Face API时,我想在其周围绘制矩形并在其上打印文本(年龄,性别)。我到底该怎么做?我在下面附加了我的代码。

import requests
# If you are using a Jupyter notebook, uncomment the following line.
#%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO

# Replace <Subscription Key> with your valid subscription key.
subscription_key = "1ed933c3d81f4b5d8b998c81f3f48cf8"
assert subscription_key

# You must use the same region in your REST call as you used to get your
# subscription keys. For example, if you got your subscription keys from
# westus, replace "westcentralus" in the URI below with "westus".
#
# Free trial subscription keys are generated in the westcentralus region.
# If you use a free trial subscription key, you shouldn't need to change
# this region.
vision_base_url = "https://japaneast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false"

analyze_url = vision_base_url + "analyze"

# Set image_path to the local path of an image that you want to analyze.
image_path = "image.jpg"

# Read the image into a byte array
image_data = open(image_path, "rb").read()
headers    = {'Ocp-Apim-Subscription-Key': subscription_key,
              'Content-Type': 'application/octet-stream'}
params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
    'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}

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()
print(analysis)
# image_caption = analysis["description"]["captions"][0]["text"].capitalize()

# Display the image and overlay it with the caption.
image = Image.open(BytesIO(image_data))
plt.imshow(image)
plt.axis("off")
plt.show()
# _ = plt.title(image_caption, size="x-large", y=-0.1)
import requests
from io import BytesIO
from PIL import Image, ImageDraw,ImageFont

def getRectangle(faceDictionary):
    rect = faceDictionary['faceRectangle']
    left = rect['left']
    top = rect['top']
    bottom = left + rect['height']
    right = top + rect['width']
    return ((left, top), (bottom, right))

def getAge(faceDictionary):
    f=faceDictionary['faceAttributes']
    age=f['age']
    return age
def getGender(faceDictionary):
    f=faceDictionary['faceAttributes']
    gender=f['gender']
    return gender
draw = ImageDraw.Draw(image)
for face in analysis:
    draw.rectangle(getRectangle(face), outline='red')
    draw.text(getRectangle(face)[1],getAge(face), fill=(255, 0, 0))

特别是给出错误的行是最后一行。     “ float”类型的参数不可迭代

但是当我说出最后一行时,代码运行正常。

0 个答案:

没有答案