Celeb Glow
general | March 18, 2026

Why am I getting import cv2 error even I have installed it properly?

I'm trying to run python script which import opencv, I have sucessfully installed opencv, I can see the installation and version but when I try to call it through the script I get import error

(cv) nikhil@nikhil-VirtualBox:~/object_detection_projects/opencv_traffic_counting$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
[1]+ Stopped python3
(cv) nikhil@nikhil-VirtualBox:~/object_detection_projects/opencv_traffic_counting$ sudo python3 traffic.py
Traceback (most recent call last): File "traffic.py", line 8, in <module> import cv2
ImportError: No module named 'cv2'

How can I fix this? I'm using Ubuntu 16.04, script I'm trying to run is

import os
import logging
import logging.handlers
import random
import numpy as np
import skvideo.io
import cv2
import matplotlib.pyplot as plt
import utils
# without this some strange errors happen
cv2.ocl.setUseOpenCL(False)
random.seed(123)
from pipeline import ( PipelineRunner, ContourDetection, Visualizer, CsvWriter, VehicleCounter)
# ============================================================================
IMAGE_DIR = "/Desktop"
VIDEO_SOURCE = "Car Detection in Traffic with Deep Learning Toolkit for LabVIEW.mp4"
SHAPE = (720, 1280) # HxW
EXIT_PTS = np.array([ [[732, 720], [732, 590], [1280, 500], [1280, 720]], [[0, 400], [645, 400], [645, 0], [0, 0]]
])
# ============================================================================
def train_bg_subtractor(inst, cap, num=500): ''' BG substractor need process some amount of frames to start giving result ''' print ('Training BG Subtractor...') i = 0 for frame in cap: inst.apply(frame, None, 0.001) i += 1 if i >= num: return cap
def main(): log = logging.getLogger("main") # creating exit mask from points, where we will be counting our vehicles base = np.zeros(SHAPE + (3,), dtype='uint8') exit_mask = cv2.fillPoly(base, EXIT_PTS, (255, 255, 255))[:, :, 0] # there is also bgslibrary, that seems to give better BG substruction, but # not tested it yet bg_subtractor = cv2.createBackgroundSubtractorMOG2( history=500, detectShadows=True) # processing pipline for programming conviniance pipeline = PipelineRunner(pipeline=[ ContourDetection(bg_subtractor=bg_subtractor, save_image=True, image_dir=IMAGE_DIR), # we use y_weight == 2.0 because traffic are moving vertically on video # use x_weight == 2.0 for horizontal. VehicleCounter(exit_masks=[exit_mask], y_weight=2.0), Visualizer(image_dir=IMAGE_DIR), CsvWriter(path='./', name='report.csv') ], log_level=logging.DEBUG) # Set up image source # You can use also CV2, for some reason it not working for me cap = skvideo.io.vreader(VIDEO_SOURCE) # skipping 500 frames to train bg subtractor train_bg_subtractor(bg_subtractor, cap, num=500) _frame_number = -1 frame_number = -1 for frame in cap: if not frame.any(): log.error("Frame capture failed, stopping...") break # real frame number _frame_number += 1 # skip every 2nd frame to speed up processing if _frame_number % 2 != 0: continue # frame number that will be passed to pipline # this needed to make video from cutted frames frame_number += 1 # plt.imshow(frame) # plt.show() # return pipeline.set_context({ 'frame': frame, 'frame_number': frame_number, }) pipeline.run()
# ============================================================================
if __name__ == "__main__": log = utils.init_logging() if not os.path.exists(IMAGE_DIR): log.debug("Creating image directory `%s`...", IMAGE_DIR) os.makedirs(IMAGE_DIR) main()
2

1 Answer

Firstly you have to check that opencv has been installed on your lepi. You can use command below to do that.

python3 -c "import cv2; print(cv2.__version__)"

It would show you the version of your opencv. But if not, maybe your opencv-python have not installed yet.Then try to use this command to install it.

sudo apt install python3-opencv

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy