Unresolved reference "cv2" inside cv2 (cv2.cv2)

Question:

I’ve looked around and people seem to have similar problems but none described my case exactly, and solutions that worked for them didn’t seem to work for me (or there was no answer to the question at all).

Using pycharm, after having installed opencv-python and opencv-contrib-python I noticed that import cv2 works, but when I tried accessing cv2.imread() pycharm complained about not being able to find it.

So I went to the cv2 init file, which looks like this:

import importlib

from .cv2 import *
from .data import *

# wildcard import above does not import "private" variables like __version__
# this makes them available
globals().update(importlib.import_module('cv2.cv2').__dict__)

Pycharm detects an unresolved reference on the from .cv2 import * line and I imagine the same problem happens on the last line – I tried doing the following in a python console:

import cv2
print(__version__)

But I got a NameError, which seems to confirm my suspicion.

As I wrote, I have tried installing opencv-contrib-python but that didn’t seem to do anything and frankly I’m already out of ideas.

Notes:
– I’m on Windows 10 x64.
– I’m using Python 3.6 x64.
– I have a virtual environment set up on my Pycharm project.

Asked By: theberzi

||

Answers:

I found out that the problem is due to how cv2’s __init__.py imports all the stuff, namely the globals().update() line.

In substance, everything does work, but since Pycharm doesn’t index that kind of call, it doesn’t detect the namespace as being properly imported. The solution would thus be to ignore the “error” and do without autocompletion.

Answered By: theberzi

Have you installed opencv via terminal?

For example, like this.

$ pip install opencv-python
$ pip install opencv-contrib-python

I also experienced the same problem.

If you use pycharm, you should install opencv via pycharm.

File -> Settings... -> Project interpreter -> +

Answered By: taront

I’m no expert but the following line worked for me:

import cv2.cv2 as cv2

Everything seems to work afterwards. Autocompletion is also back

Answered By: Xaaris

I got this same issue. You need to try a couple of things.

  1. You need to simply import cv2 instead of cv2.cv2. Simply write "import cv2"
  2. If you have installed any other library such as cv before, then uninstall it first.
  3. The library that we need to install is opencv-python
  4. You need to install it via IDE not with the terminal. Steps are as follows:
    File -> Settings -> (Click on your project) -> Project Interpreter -> + -> (Type opencv-python) -> Download and install it -> It should work now.
Answered By: Hassan Shahzad

From Python Interpreter download the version of opencv-python 4.5.4.60 and opencv-contrib-python 4.5.5.64.

Answered By: Muhammad Ojagzada