Jupyter Notebook中导入cv2库出现ModuleNotFoundError问题求助
Fixing "ModuleNotFoundError: No module named 'cv2'" in Jupyter Notebook (Works in Cmd)
Hey there, let's troubleshoot this super common environment mismatch issue—here's why your Jupyter can't find cv2 even though it works in the regular cmd Python shell, and how to fix it:
Step 1: Confirm the Environment Mismatch
First, let's verify that Jupyter is using a different Python environment than your cmd session:
- In your cmd Python shell, run:
Note down the path (e.g.,import sys print(sys.executable)C:\Users\YourName\anaconda3\python.exe). - Open Jupyter Notebook, create a new Python notebook, and run the exact same code. If the paths don't match, that's the root cause—Jupyter is pointing to a Python environment where
cv2isn't installed.
Step 2: Fixes to Try
Option 1: Install cv2 Directly in Jupyter's Environment
If you want to get up and running quickly, you can install opencv-python directly from within Jupyter:
- In your notebook, run this shell command (the
!tells Jupyter to execute it as a terminal command):!pip install opencv-python - After installation, restart your Jupyter kernel (click "Kernel" > "Restart" in the top menu), then try
import cv2again.
Option 2: Link Your Anaconda Environment to Jupyter
If you installed cv2 in a specific Anaconda virtual environment (like base or a custom env), you can add that environment to Jupyter's kernel list:
- Open cmd and activate the environment where
cv2is installed:conda activate your_env_name # Replace "your_env_name" with your actual environment name (e.g., base) - Install the
ipykernelpackage (this lets Jupyter use your environment):conda install ipykernel - Register the environment with Jupyter:
python -m ipykernel install --user --name your_env_name --display-name "Python (your_env_name)" - Close and reopen Jupyter Notebook. When creating a new notebook, select the
Python (your_env_name)kernel—import cv2should work now.
Option 3: Launch Jupyter from the Correct Environment
The simplest way to ensure Jupyter uses your cv2-enabled environment is to start it directly from that environment:
- Open cmd, activate your environment with
conda activate your_env_name. - Run
jupyter notebookto launch Jupyter. - Any notebooks you open in this session will use the environment where
cv2is installed, so imports will work.
内容的提问来源于stack exchange,提问作者Moid




