AWS Lambda allows you to run code without provisioning or managing servers. One common use case is to handle image processing tasks such as object detection, image transformation, and computer vision tasks with OpenCV.
However, OpenCV is a large library, and packaging it with your Lambda function code can be tricky because Lambda has a size limit for deployment packages.
A better and only approach is to use Lambda Layers, which enable you to reuse common libraries across multiple functions. I have struggled a lot when trying to create a layer for opencv-python
so that I can use cv2
and numpy
in my code. There are some documents, repos out there but they are all outdated.
In this blog post, I will show you how to create an OpenCV layer for AWS Lambda in 2025.
Step by step
First let's make a folder. The important thing is the python version here. You need to change the version based on the version of the Lambda function.
Here I'm using Python 3.11:
mkdir -p opencv-layer/python/lib/python3.11/site-packages/
cd opencv-layer
Next, you download all packages. Remember to change the Python version.
You need to change both versions in the command below.
Change between pip
and pip3
based on your enviroment.
The key part here is using the --platform manylinux2014_x86_64
flag which ensures compatibility with Lambda's environment, which is Linux.
Package opencv-python
is too big, over the limit 150MB.
Use opencv-python-headless
instead of the standard opencv-python
package since Lambda doesn't need GUI components, the size of the layer will be reduced a lot which is good.
pip3 install --platform manylinux2014_x86_64 --implementation cp --python-version 3.11 --only-binary=:all: --upgrade --target python/lib/python3.11/site-packages/ opencv-python-headless
Then you will have a folder look liek this, for this one I use Python 3.11:
Create a ZIP file of the layer contents.
If you are on Window, you can manually zip the python
folder.
zip -r opencv-layer.zip python/
Publish the layer.
You can also upload the zip file to S3 and create the layer manually with AWS console.
aws lambda publish-layer-version \
--layer-name opencv-layer \
--description "OpenCV layer" \
--zip-file fileb://opencv-layer.zip \
--compatible-runtimes python3.11
Finally now you just need to add the layer to the Lambda function you want. Make sure that they have the same Python version.
Test the layer
You can use this simple code to make sure that the layer is working.
import cv2
import numpy
def lambda_handler(event, context):
print(cv2.__version__)
print(numpy.__version__)
Hope this blog would be helpful!
Thank you for reading!
Top comments (0)