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.
OpenCV comes preinstalled on Google colab. Simply import cv2 and use it.
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:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With