If you are trying to display OpenCV image using matplotlib, use the code below.
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline # if you are running this code in Jupyter notebook
# reads image 'opencv-logo.png' as grayscale
img = cv2.imread('/path_to_image/opencv-logo.png', 0)
plt.imshow(img, cmap='gray')
Answer from An unfinished seeker on Stack OverflowIf you are trying to display OpenCV image using matplotlib, use the code below.
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline # if you are running this code in Jupyter notebook
# reads image 'opencv-logo.png' as grayscale
img = cv2.imread('/path_to_image/opencv-logo.png', 0)
plt.imshow(img, cmap='gray')
There is a tutorial on Getting Started with Images.
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('/path_to_image/messi5.jpg',0)
# Show the image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Use an absolute path to the image, and then you don't have any path problems.
Absolute and relative paths
OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow
What cap.read() returns is a boolean (True/False) and image content. If you remove success, the img variable takes that boolean and image data as a tuple. This is why you get an error.
.read() in OpenCV returns 2 things, boolean and data. If there are not 2 variables, a tuple will be assigned to one variable. The boolean is mostly used for error catching. Assigning a tuple to 1 var with 2 data items can sometimes be useful, but in this instance, you should create 2 vars and split the data into 2 variables to make it easier.
If you do not want to assign the bool to a var, you can use _ as the variable name.
cap.read() returns a tuple, which contains a boolean success flag, and the video frame.
if the video has ended, the success flag is False. in that case, the frame is empty.
you MUST test that flag and end the loop.
the tutorial you watched failed to do so. it taught you wrong.
in addition, you must check if cap.isOpened() because opening the video file (or camera) could have failed, and you need to react to that.
here is the proper code:
cap = cv2.VideoCapture(...) # open a video file or camera
assert cap.isOpened(), "file/camera could not be opened!"
while True:
(success, img) = cap.read() # cap.read() always returns a tuple of two things
if not success: break # you absolutely must check this
cv2.imshow("Video", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break