How can i using local photo for processing in Face API calling (Microsoft Cognitive Services) using Python

447 views Asked by At

Update:

I have used the face_client.face.detect_with_url before and it worked.So my network should be fine (maybe, I guess). However, when I switched to the face_client.face.detect_with_stream, it still got the errors... Finally, I rewrote my code with referring to Azure Detect faces API, how to change the URL picture to a local picture?, and it could operate successfully. I'm still not sure why the previous question happened, but your advices @ Jim Xu, @ Satya V are appreciated!


After passing the official example (Microsoft Cognitive Services) to do the face detection via python. I have tried to detect the face with a local image. However, i am getting some errors....

The official codeļ¼š

group_photo = 'test-image-person-group.jpg'
IMAGES_FOLDER = os.path.join(os.path.dirname(os.path.realpath(__file__)))
# Get test image
test_image_array = glob.glob(os.path.join(IMAGES_FOLDER, group_photo))
image = open(test_image_array[0], 'r+b')

# Detect faces
face_ids = []
faces = face_client.face.detect_with_stream(image)

Refer to the official code, My code is:

IMAGES_FOLDER='' #the image path
test_image_array = glob.glob(os.path.join(IMAGES_FOLDER, '*jpg'))
image = open(test_image_array[0], 'r+b')
faces = face_client.face.detect_with_stream(image)

However, there are some error

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    466 
--> 467                     low_conn.endheaders()
    468 

~/.conda/envs/Emotion_Azure/lib/python3.8/http/client.py in endheaders(self, message_body, encode_chunked)
   1249             raise CannotSendHeader()
-> 1250         self._send_output(message_body, encode_chunked=encode_chunked)
   1251 

~/.conda/envs/Emotion_Azure/lib/python3.8/http/client.py in _send_output(self, message_body, encode_chunked)
   1009         del self._buffer[:]
-> 1010         self.send(msg)
   1011 

~/.conda/envs/Emotion_Azure/lib/python3.8/http/client.py in send(self, data)
    949             if self.auto_open:
--> 950                 self.connect()
    951             else:

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/urllib3/connection.py in connect(self)
    361 
--> 362         self.sock = ssl_wrap_socket(
    363             sock=conn,

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/urllib3/util/ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir, key_password, ca_cert_data)
    396 
--> 397     return context.wrap_socket(sock)
    398 

~/.conda/envs/Emotion_Azure/lib/python3.8/ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    499         # ctx._wrap_socket()
--> 500         return self.sslsocket_class._create(
    501             sock=sock,

~/.conda/envs/Emotion_Azure/lib/python3.8/ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
   1039                         raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
-> 1040                     self.do_handshake()
   1041             except (OSError, ValueError):

~/.conda/envs/Emotion_Azure/lib/python3.8/ssl.py in do_handshake(self, block)
   1308                 self.settimeout(None)
-> 1309             self._sslobj.do_handshake()
   1310         finally:

OSError: [Errno 0] Error

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/universal_http/requests.py in send(self, request, **kwargs)
    138         try:
--> 139             response = session.request(
    140                 request.method,

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    529         send_kwargs.update(settings)
--> 530         resp = self.send(prep, **send_kwargs)
    531 

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/sessions.py in send(self, request, **kwargs)
    642         # Send the request
--> 643         r = adapter.send(request, **kwargs)
    644 

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    497         except (ProtocolError, socket.error) as err:
--> 498             raise ConnectionError(err, request=request)
    499 

ConnectionError: [Errno 0] Error

During handling of the above exception, another exception occurred:

ClientRequestError                        Traceback (most recent call last)
<ipython-input-15-122d5fe49d09> in <module>
----> 1 faces = face_client.face.detect_with_stream(image)

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/azure/cognitiveservices/vision/face/operations/_face_operations.py in detect_with_stream(self, image, return_face_id, return_face_landmarks, return_face_attributes, recognition_model, return_recognition_model, detection_model, custom_headers, raw, callback, **operation_config)
    786         # Construct and send request
    787         request = self._client.post(url, query_parameters, header_parameters, body_content)
--> 788         response = self._client.send(request, stream=False, **operation_config)
    789 
    790         if response.status_code not in [200]:

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/service_client.py in send(self, request, headers, content, **kwargs)
    334         kwargs.setdefault('stream', True)
    335         try:
--> 336             pipeline_response = self.config.pipeline.run(request, **kwargs)
    337             # There is too much thing that expects this method to return a "requests.Response"
    338             # to break it in a compatible release.

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/pipeline/__init__.py in run(self, request, **kwargs)
    195         pipeline_request = Request(request, context)  # type: Request[HTTPRequestType]
    196         first_node = self._impl_policies[0] if self._impl_policies else self._sender
--> 197         return first_node.send(pipeline_request, **kwargs)  # type: ignore
    198 
    199 class HTTPSender(AbstractContextManager, ABC, Generic[HTTPRequestType, HTTPResponseType]):

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/pipeline/__init__.py in send(self, request, **kwargs)
    148         self._policy.on_request(request, **kwargs)
    149         try:
--> 150             response = self.next.send(request, **kwargs)
    151         except Exception:
    152             if not self._policy.on_exception(request, **kwargs):

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/pipeline/requests.py in send(self, request, **kwargs)
     70         try:
     71             try:
---> 72                 return self.next.send(request, **kwargs)
     73             except (oauth2.rfc6749.errors.InvalidGrantError,
     74                     oauth2.rfc6749.errors.TokenExpiredError) as err:

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/pipeline/requests.py in send(self, request, **kwargs)
    135 
    136         try:
--> 137             return self.next.send(request, **kwargs)
    138         finally:
    139             if old_max_redirects:

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/pipeline/__init__.py in send(self, request, **kwargs)
    148         self._policy.on_request(request, **kwargs)
    149         try:
--> 150             response = self.next.send(request, **kwargs)
    151         except Exception:
    152             if not self._policy.on_exception(request, **kwargs):

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/pipeline/requests.py in send(self, request, **kwargs)
    191         return Response(
    192             request,
--> 193             self.driver.send(request.http_request, **kwargs)
    194         )

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/universal_http/requests.py in send(self, request, **kwargs)
    331         """
    332         requests_kwargs = self._configure_send(request, **kwargs)
--> 333         return super(RequestsHTTPSender, self).send(request, **requests_kwargs)
    334 
    335 

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/universal_http/requests.py in send(self, request, **kwargs)
    143         except requests.RequestException as err:
    144             msg = "Error occurred in request."
--> 145             raise_with_traceback(ClientRequestError, msg, err)
    146 
    147         return RequestsClientResponse(request, response)

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/exceptions.py in raise_with_traceback(exception, message, *args, **kwargs)
     49     error = exception(exc_msg, *args, **kwargs)
     50     try:
---> 51         raise error.with_traceback(exc_traceback)
     52     except AttributeError:
     53         error.__traceback__ = exc_traceback

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/msrest/universal_http/requests.py in send(self, request, **kwargs)
    137         session = kwargs.pop('session', self.session)
    138         try:
--> 139             response = session.request(
    140                 request.method,
    141                 request.url,

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    528         }
    529         send_kwargs.update(settings)
--> 530         resp = self.send(prep, **send_kwargs)
    531 
    532         return resp

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/sessions.py in send(self, request, **kwargs)
    641 
    642         # Send the request
--> 643         r = adapter.send(request, **kwargs)
    644 
    645         # Total elapsed time of the request (approximately)

~/.conda/envs/Emotion_Azure/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    496 
    497         except (ProtocolError, socket.error) as err:
--> 498             raise ConnectionError(err, request=request)
    499 
    500         except MaxRetryError as e:

ClientRequestError: Error occurred in request., ConnectionError: [Errno 0] Error

How can i fix it? Did I miss something or make a mistake?

0

There are 0 answers