Rifaye Ibrahim
Rifaye Ibrahim

Reputation: 11

How to transform this code into a function def()

How do I transform this into a function def()

detected_faces1 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03')
    source_image1_id = detected_faces1[0].face_id
    print('{} face(s) detected from image {}.'.format(len(detected_faces1), source_image_file_name1))

I tried doing this:

def detected_faces1():
    face_client.face.detect_with_url(IMAGE_BASE_URL, detection_model='detection_03')
    source_image1_id = detected_faces1[0].face_id
print('{} face(s) detected from image.'.format(len(detected_faces1)))

But I get an error:

TypeError: 'function' object is not subscriptable

Upvotes: 0

Views: 65

Answers (3)

infin1tum
infin1tum

Reputation: 1

You need to return detected_faces1 in the function in order to access it.

def detected_faces1():
    detected_faces1 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03')
    source_image1_id = detected_faces1[0].face_id
    return detected_faces1

print('{} face(s) detected from image {}.'.format(len(detected_faces1()), source_image_file_name1))

If you want to return multiple elements from a function you can use an array OR dictionary.

Example array:

def detected_faces1():
    detected_faces1 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03')
    source_image1_id = detected_faces1[0].face_id
    return [detected_faces1, source_image1_id]

data = detected_faces1()

data[0] will be detected_faces1 and data[1] will be source_image1_id.

Example dictionary:

def detected_faces1():
    detected_faces1 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03')
    source_image1_id = detected_faces1[0].face_id
    return {'faces': detected_faces1, 'source_image1_id': source_image1_id}
data = detected_faces1()

You can access the values using data[key] e.g data['faces'].

Upvotes: 0

pppig
pppig

Reputation: 1275

Your detected_faces1 is a function, you can't pass it directly to the len function, you should execute it and pass the result, like this len(detected_faces1()).

Also, your function will return None (the default), you need to return xx to return the result you want.

def detected_faces1():
    return face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03')
    # source_image1_id = detected_faces1[0].face_id
     

print('{} face(s) detected from image {}.'.format(len(detected_faces1()), source_image_file_name1))

Upvotes: 1

chapter473
chapter473

Reputation: 15

You have two objects both named detected_faces1 - one is a list and the other is a function.

Update it and it should fix your issue

Upvotes: 0

Related Questions