Run Python + OpenCV + dlib in Azure Functions

2019-03-31 03:47发布

问题:

I have created an image processing script in Python (with dlib and OpenCV) - I was wondering how I can bring this functionality to Azure Functions, so that the script can be called via an API. As Python is still in preview for Azure Functions I wanted to know if anybody here has experience with bringing modules to Azure Functions and if it's possible to install OpenCV there?

回答1:

You can bring your own modules to your Function by uploading them into the a lib folder residing in the same folder as your Function.

However, in the context of OpenCV, it is not a supported scenario at the moment. The default Python version being used in the Azure Function environment is Python 2.7. If you try to execute a Function code using OpenCV for Python 2.7, the error message you will get would be similar to the following,

2016-11-07T20:47:33.151 Function completed (Failure, Id=42fa9d38-05f1-46d4-a8ce-9fbaa24a870d)
2016-11-07T20:47:33.166 Exception while executing function: Functions.ImageProcessor. Microsoft.Azure.WebJobs.Script: ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
  File "D:\home\site\wwwroot\ImageProcessor\run.py", line 17, in <module>
    import cv2
ImportError: numpy.core.multiarray failed to import

The fix for this is to update the numpy version used by Python 2.7, but you will not be able to run the update yourself.

As you have noted, Python language support for Azure Functions is in an experimental stage right now. These issues will be addressed when Python is fully on-boarded as a first-class language.



回答2:

so I figured a dirty hack, it will install the package on the first run and throw an error, so the function will restart. Follow these steps:

  1. Upload package to the function directory (I just added the package to the git project to which the function is syncronized).
  2. Do something like (there probably is a better way, but I'm really new to python):

    try:
     import pyodbc
    except:
     package = 'pyodbc-3.0.10-cp27-none-win32.whl'
     pip.main(['install', '--user', package])
     raise ImportError('Restarting')
    

So the reason behind --user is that it won't let me install it with admin privileges... Also if you do include the requirements.txt with your git repository the packages are installed to the WebApp, but it appears that the Function got its own python environment, so you have to install packages manually.

So the only real trick it to find the appropriate wheel package (I strongly believe that Function is using Python 2.7, I couldn't get it to work with packages for Python 3.4)