To install OpenCV in Python, you can follow the below steps:
- Ensure that you have Python installed on your system. You can check by running the command
python --versionin the command prompt or terminal.
- Install OpenCV using pip, which is a package manager for Python. Run the command
pip install opencv-pythonin the command prompt or terminal.
- 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.
- Once the installation is complete, you can import OpenCV in your Python code using the command
- 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.
If you are using Anaconda, you can install OpenCV using the Anaconda prompt by following the below steps:
- Open the Anaconda prompt by searching for “Anaconda prompt” in the start menu.
- Create a new environment for OpenCV using the command
conda create --name opencv.
- Activate the environment using the command
conda activate opencv.
- Install OpenCV using the command
conda install -c conda-forge opencv.
- Once the installation is complete, you can open a Python interpreter and import OpenCV using the command
- 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.