How to import cv2 in python3?

14 min read

To import cv2 in Python3, you need to follow these steps:

  1. Install OpenCV on your computer. To do this, run the following command in your terminal:
pip3 install opencv-python
  1. Once OpenCV is installed, launch the Python3 shell in your terminal and type the following command to import cv2:
import cv2
  1. You can now use cv2 functions and classes in your Python3 code. For example, the following code will open a video file and display the frames in a window:
import cv2

cap = cv2.VideoCapture('video.avi')

while(cap.isOpened()):
    ret, frame = cap.read()
    
    cv2.imshow('frame',frame)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Note: If you encounter any errors while importing cv2, make sure that OpenCV is installed correctly on your computer, and that your Python environment is properly configured.