0

I recently learned about the concept of building docker images based on a multi-staged Dockerfile.
I have been trying simple examples of multi-staged Dockerfiles, and they were working fine. However, when I tried implementing the concept for my own application, I was facing some issues.
My application is about object detection in videos, so I use python and Tensorflow.

Here is my Dockerfile:

FROM python:3-slim AS base

WORKDIR /objectDetector

COPY detect_objects.py .
COPY detector.py .
COPY requirements.txt .
ADD data /objectDetector/data/
ADD models /objectDetector/models/

RUN apt-get update && \
    apt-get install protobuf-compiler -y && \
    apt-get install ffmpeg libsm6 libxext6 -y && \
    apt-get install gcc -y

RUN pip3 install update && python3 -m pip install --upgrade pip
RUN pip3 install tensorflow-cpu==2.9.1
RUN pip3 install opencv-python==4.6.0.66
RUN pip3 install opencv-contrib-python

WORKDIR /objectDetector/models/research
RUN protoc object_detection/protos/*.proto --python_out=.
RUN cp object_detection/packages/tf2/setup.py .
RUN python -m pip install .
RUN python object_detection/builders/model_builder_tf2_test.py

WORKDIR /objectDetector/models/research
RUN pip3 install wheel && pip3 wheel . --wheel-dir=./wheels 

FROM python:3-slim
RUN pip3 install update && python3 -m pip install --upgrade pip
COPY --from=base /objectDetector /objectDetector
WORKDIR /objectDetector
RUN pip3 install --no-index --find-links=/objectDetector/models/research/wheels -r requirements.txt

When I try to run my application in the final stage of the container, I receive the following error:

root@3f062f9a5d64:/objectDetector# python detect_objects.py 
Traceback (most recent call last):
  File "/objectDetector/detect_objects.py", line 3, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'

So per my understanding, it seems that opencv-python is not successfully moved from the 1st stage to the 2nd.
I have been searching around, and I found some good blogs and questions tackling the issue of multi-staging Dockerfiles, specifically for python libraries. However, it seems I missing something here.

Here are some references that I have been following to solve the issue:

So my question is: How can we use opencv in a multistage docker image?

philippos
  • 1,142
  • 5
  • 20
  • 41

0 Answers0