How to Install OpenCV in Anaconda

A step by step guide to Installing OpenCV in Anaconda

Updated March 15, 2024


Hey! If you love Computer Vision and AI, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

How to Install OpenCV in Anaconda

If you’re working with computer vision and image processing in Python, OpenCV is an essential library to have in your toolkit. In this post, we’ll walk through the steps to install OpenCV in an Anaconda environment, making it easy to manage your packages and dependencies.

Prerequisites

Before we begin, make sure you have the following installed:

  • Python (version 3.6 or higher)
  • Anaconda (or Miniconda)

Step 1: Create a New Anaconda Environment

It’s always a good practice to create a separate environment for each project to avoid conflicts between package versions. Let’s create a new Anaconda environment for our OpenCV project.

Open your terminal or Anaconda Prompt and run the following command:

conda create --name opencv_env python=3.8

This command creates a new environment named opencv_env with Python 3.8 as the default interpreter.

Step 2: Activate the Environment

To use the newly created environment, we need to activate it. Run the following command:

conda activate opencv_env

Your terminal prompt should now show the name of the activated environment.

Step 3: Install OpenCV

Now that we have our environment set up, let’s install OpenCV. With Anaconda, installing OpenCV is straightforward. Run the following command:

conda install -c conda-forge opencv

This command installs OpenCV from the conda-forge channel, which provides a wide range of packages for scientific computing.

Step 4: Verify the Installation

To verify that OpenCV is installed correctly, let’s write a simple Python script to display an image using OpenCV.

Create a new Python file named test_opencv.py and add the following code:

import cv2

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

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

Make sure to replace 'image.jpg' with the path to an image file of your choice.

Now, run the script using the following command:

python test_opencv.py

If OpenCV is installed correctly, you should see a window displaying the image you specified.

Conclusion

Congratulations! You have successfully installed OpenCV in an Anaconda environment. With OpenCV, you can now dive into the world of computer vision and image processing using Python.

Remember to activate the opencv_env environment whenever you want to work on projects that require OpenCV.

Happy coding!