How to install OpenCV in Python

To install OpenCV in Python, you can follow the below steps:

  1. Ensure that you have Python installed on your system. You can check by running the command python --version in the command prompt or terminal.
  2. Install OpenCV using pip, which is a package manager for Python. Run the command pip install opencv-python in the command prompt or terminal.
  3. If you need additional modules, you can install them using pip as well. For example, if you need the contrib module, you can run the command pip install opencv-contrib-python.
  4. Once the installation is complete, you can import OpenCV in your Python code using the command import cv2.
  5. To verify that OpenCV is installed correctly, you can run a sample code that displays an image. Here is a sample code:
import cv2

# Load an image
img = cv2.imread('sample.jpg')

# Display the image
cv2.imshow('Image', img)

# Wait for a key press and then close the window
cv2.waitKey(0)
cv2.destroyAllWindows()

Make sure that you replace the file name 'sample.jpg' with the name of an actual image file on your system.

Using Anaconda:

If you are using Anaconda, you can install OpenCV using the Anaconda prompt by following the below steps:

  1. Open the Anaconda prompt by searching for “Anaconda prompt” in the start menu.
  2. Create a new environment for OpenCV using the command conda create --name opencv.
  3. Activate the environment using the command conda activate opencv.
  4. Install OpenCV using the command conda install -c conda-forge opencv.
  5. Once the installation is complete, you can open a Python interpreter and import OpenCV using the command import cv2.
  6. To verify that OpenCV is installed correctly, you can run the same sample code as mentioned in the previous answer.

Note: In Anaconda, you can also use the Anaconda Navigator to manage environments and packages. You can create a new environment, activate it, and install OpenCV using the GUI interface.