Skip to content

Instantly share code, notes, and snippets.

@mmitou
Last active August 20, 2017 02:40
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mmitou/2299686a8771495dcd67 to your computer and use it in GitHub Desktop.
Save mmitou/2299686a8771495dcd67 to your computer and use it in GitHub Desktop.

AWS LambdaのPythonから利用出来るOpenCV3.0のライブラリを作成する手順

AWS Lambdaの実行環境の確認

AWSのLambda 実行環境と利用できるライブラリで確認する。

2015年12月現在では、 AMI ID: アジアパシフィック(東京) リージョンの ami-cbf90ecb を使っている。

OpenCVのビルド環境を作る

Using Packages and Native nodejs Modules in AWS Lambdaを参考にしている。 EC2でami-cbf90ecbからインスタンスを起動して、以下のコマンドを実行し、ビルドに必要な環境を作る。

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

numpyをインストールしてOpenCVをビルドする

ec2-userのホームディレクトリにopencv-3.0.0.zipが保存してある事を前提とする。 Lambdaで実行しやすくする為、共有ライブラリを作らない。 ビルド用インスタンスにログインし、以下の通りコマンドを実行する。

cd 
virtualenv project
source project/bin/activate
pip install numpy
mkdir local
unzip opencv-3.0.0.zip
cd opencv-3.0.0
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_SHARED_LIBS=NO -D BUILD_opencv_python2=ON -D CMAKE_INSTALL_PREFIX=~/local ~/opencv-3.0.0
make
make install
cp ~/local/lib/python2.7/site-packages/cv2.so ~/project/lib64/python2.7/site-packages/

numpyとOpenCVをバンドルしたコードをzipにまとめる

例として、hello.pyをAWS Lambdaで実行する。

hello.py

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

以下のコマンドを実行して、hello.pyとhello.pyの依存するパッケージをzipにまとめる。

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://<バケット名>/bundle.zip

AWS Lambdaで実行する

AWS LambdaのコンソールからLambdaを実行する。

@mmerchant
Copy link

Thank you for posting this. I get the error message:

Unable to import module 'hello': liblapack.so.3: cannot open shared object file: No such file or directory

@mmitou
Copy link
Author

mmitou commented Dec 16, 2015

hi.

Will you confirm your AWS Lambda configuration If your bundle.zip includes hello.py ?

go to 'Lambda > Functions > "your lambda function name"' , click 'configuration' tab,
and confirm that Handler form is filled with 'hello.lambda_handler'.

@jcrowe206
Copy link

@mmerchant did you ever solve this issue? I'm having the same problem

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