Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google colab python3 name cv2 is not defined

I imported all the required libraries and tried to do a simple image reconginition program with opencv but the error cv2 not defined shows up but as it is visible from the first cell that open cv is installed and no import errors are shown as I have already done the !apt updates and the version I have is 3.4.0. Any help on the program attached below would be appreciated. Thanks in advance.

enter image description here

like image 932
bharath k Avatar asked Feb 14 '19 21:02

bharath k


People also ask

Does Google colab have cv2?

OpenCV comes preinstalled on Google colab. Simply import cv2 and use it.


2 Answers

First, I recommend you to get yourself familiar with Jupyter notebooks and how they work. Then, the first problem you had it was because you were trying to run a cell that uses cv2 without running the import cv2 before. The second problem you are facing is because you cannot use cv2.imshow(...), since it requires an X server which is not available. Below, you can see an MCVE in which you can upload an image, use OpenCV to read and change it, and display images:

import cv2
import matplotlib.pyplot as plt
# %matplotlib inline

from google.colab import files
uploaded = files.upload()

img = cv2.imread('lenna.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

fig, ax = plt.subplots(ncols=2)

ax[0].imshow(img[..., ::-1])  # BGR to RGB
ax[0].set_title('Original image')

ax[1].imshow(gray_img, cmap=plt.cm.gray)
ax[1].set_title('Grayscale image')

plt.show()

If you run on Google Colab, it will look like this:

colab example

like image 164
Berriel Avatar answered Oct 20 '22 10:10

Berriel


You can use this solution if you're using google colab:

from google.colab.patches import cv2_imshow

image = cv2.imread('image.png')

cv2_imshow( image)

cv2.waitKey(0)

cv2.destroyAllWindows()
like image 22
Wahib Mzali Avatar answered Oct 20 '22 11:10

Wahib Mzali