It just happened to me and I solved it installing both opencv-python and opencv-python-headless with pip and reloading the Visual Studio Code window right after it.
To install the needed packages, just run this command in the terminal:
Copy$ pip install opencv-python opencv-python-headless
Answer from Sergio Tabares on Stack OverflowIt just happened to me and I solved it installing both opencv-python and opencv-python-headless with pip and reloading the Visual Studio Code window right after it.
To install the needed packages, just run this command in the terminal:
Copy$ pip install opencv-python opencv-python-headless
I had a similar issue so I installed opencv-python-headless (install opencv-python if not earlier) and reloaded the VScode window.
Copypip install opencv-python-headless
However, some methods like imshow() kept failing:
Copycv2.error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'
This was resolved by installing opencv-contrib-python. You can install it by running the following code in your terminal:
Copypip install opencv-contrib-python
Videos
So I installed OpenCV and pip via cmd, and I installed the newest Python version 3.9. I also write my code on Visual Studio Code. Basically whenever I try to run it in VS Code, this error shows up, meanwhile when I open it outside of VS Code, only a window pops up and disappears after 1 second.
What can be the reason? I also should mention that I have the Python file and OpenCV files in different places
According to your description, I think there should be multiple versions of Python in your system.
You could use "ctrl+shift+P" to choose your python interpreter.

You can also use pip's command to install opencv into the current Python package floder.
pip install -t FloderPath opencv-python
Two reasons come to mind:
1.) Either the path to the opencv library is not set in the editor so it cannot find it. That happens sometimes if you changed settings in the runtime environment.
2.) Or you created a virtual environment prior to installing opencv. In that case, install opencv for your virtual environment as well.
It is difficult to tell what is going on with so little information. The above causes are just the most likely. Check your runtime environment and your library paths.