python已经安装过包,仍出现引入import报错


问题描述

python安装过package之后仍然报错:

python安装完opencv-python 之后,import cv2 标红

在这里插入图片描述

终端显示已经重新安装了opencv-python

PS C:developpython_workspacelearn_pytorch> pip install opencv-python==4.5.1.48 matplo
tlib -i https://pypi.douban.com/simple
Looking in indexes: https://pypi.douban.com/simple
Collecting opencv-python==4.5.1.48
  Downloading https://mirrors.cloud.tencent.com/pypi/packages/3d/ae/9d9ea53f6e0288bbb494
e22f0cd73f3f9ac2ea1b9a1b7889ccc1ceaa3c1f/opencv_python-4.5.1.48-cp39-cp39-win_amd64.whl 
(34.9 MB)
     |████████████████████████████████| 34.9 MB 1.1 MB/s
Requirement already satisfied: matplotlib in c:developanaconda3libsite-packages (3.5
.1)
Requirement already satisfied: numpy>=1.19.3 in c:developanaconda3libsite-packages (
from opencv-python==4.5.1.48) (1.19.5)
Requirement already satisfied: pyparsing>=2.2.1 in c:developanaconda3libsite-package
s (from matplotlib) (3.0.4)
Requirement already satisfied: packaging>=20.0 in c:developanaconda3libsite-packages
 (from matplotlib) (21.3)
Requirement already satisfied: kiwisolver>=1.0.1 in c:developanaconda3libsite-packag
es (from matplotlib) (1.3.2)
Requirement already satisfied: cycler>=0.10 in c:developanaconda3libsite-packages (f
rom matplotlib) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:developanaconda3libsite-packag
es (from matplotlib) (4.25.0)
Requirement already satisfied: python-dateutil>=2.7 in c:developanaconda3libsite-pac
kages (from matplotlib) (2.8.2)
Requirement already satisfied: pillow>=6.2.0 in c:developanaconda3libsite-packages (
Requirement already satisfied: six>=1.5 in c:developanaconda3libsite-packages (from 
python-dateutil>=2.7->matplotlib) (1.16.0)
Installing collected packages: opencv-python
  Attempting uninstall: opencv-python
    Found existing installation: opencv-python 4.5.5.64
      Successfully uninstalled opencv-python-4.5.5.64
Successfully installed opencv-python-4.5.1.48


原因分析:

后来才发现包安装在了base环境中

Requirement already satisfied: six>=1.5 in c:developanaconda3libsite-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
安装默认base环境中c:developanaconda3libsite-packages,虚拟环境隔离掉了

输入where pipwhere python没有任何输出,虚拟环境没有被正确识别。


解决方案:

提示:从Anaconda Prompt (anaconda3)中进入虚拟环境

开始菜单->Anaconda Prompt (anaconda3)

激活pytorch虚拟环境,
输入conda activate pytorch
输入where pip,此时有了两个pip路径
在这里插入图片描述
安装包pip install opencv-python==4.5.1.48 -i https://pypi.douban.com/simple

(pytorch) C:developpython_workspacelearn_pytorch>pip install opencv-python==4.5.1.48 -i https://pypi.douban.com/simple
Looking in indexes: https://pypi.douban.com/simple
Requirement already satisfied: opencv-python==4.5.1.48 in c:developanaconda3envspytorchlibsite-packages (4.5.1.48)
Requirement already satisfied: numpy>=1.17.3 in c:developanaconda3envspytorchlibsite-packages (from opencv-python==4.5.1.48) (1.24.1)

(pytorch) C:developpython_workspacelearn_pytorch>

此时发现包已经安装在了虚拟环境下c:developanaconda3envspytorchlibsite-packages
import package不会报错。
在这里插入图片描述