简体   繁体   中英

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

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))

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

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] eg data['faces'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM