Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save joseph-zhong/372a47bb618111dcd2c81008d00357b2 to your computer and use it in GitHub Desktop.
Save joseph-zhong/372a47bb618111dcd2c81008d00357b2 to your computer and use it in GitHub Desktop.
Building OpenCV for AWS Lambda Python

To build OpenCV3.0 for AWS Lambda Python

Summary

Because AWS Lambda runs in a Amazon Linux environment, to run external modules you must

Create the OpenCV build environment

sudo yum update -y
sudo yum install gcc-c++ cmake python27-pip -y

To build the OpenCV run the following in the home directory of the EC2

  1. Download OpenCV
  2. Create a project virtual environment and install numpy
  3. Build OpenCV
cd 
wget https://github.com/opencv/opencv/archive/3.2.0.zip
virtualenv project
source project/bin/activate
pip install numpy
mkdir local
unzip opencv-3.2.0.zip
cd opencv-3.2.0
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_SHARED_LIBS=NO -D WITH_FFMPEG=ON -D BUILD_opencv_python2=ON -D CMAKE_INSTALL_PREFIX=~/local ~/opencv-3.2.0
make
make install
cp ~/local/lib/python2.7/site-packages/cv2.so ~/project/lib64/python2.7/site-packages/

As an example, to run the hello.py in AWS Lambda.

from __future__ import print_function

import cv2
import numpy as np
import boto3

def lambda_handler(event, context):
    print(cv2.__version__)
    print(np.__version__)
    print("hello")
    return event['key1']  # Echo back the first key value

Run the following command to zip the dependencies and hello.py and upload to s3

Important Note: The script must be world readable

chmod u=rwx,go=r hello.py
zip -9 bundle.zip hello.py 
cd $VIRTUAL_ENV/lib/python2.7/site-packages
zip -r9 ~/bundle.zip *
cd $VIRTUAL_ENV/lib64/python2.7/site-packages/
zip -r9 ~/bundle.zip *
cd
aws s3 cp bundle.zip s3://<S3 BUCKET HERE>/S3/KEY/HERE/bundle.zip

This will allow you to run manual tests in AWS Lambda via the console

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment