imread , then the likely cause of the error is an invalid file path supplied to cv2. imread . The cv2. imread function does not explicitly throw an error message if you give it an invalid file path (i.e., a path to a nonexistent file).
To read and display image using OpenCV Python, you could use cv2. imread() for reading the image to a variable and cv2. imshow() to display the image in a separate window.
imshow()
only works with waitKey()
:
import cv2
img = cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow', img)
cv2.waitKey()
(The whole message-loop necessary for updating the window is hidden in there.)
I found the answer that worked for me here: http://txt.arboreus.com/2012/07/11/highgui-opencv-window-from-ipython.html
If you run an interactive ipython session, and want to use highgui windows, do cv2.startWindowThread() first.
In detail: HighGUI is a simplified interface to display images and video from OpenCV code. It should be as easy as:
import cv2
img = cv2.imread("image.jpg")
cv2.startWindowThread()
cv2.namedWindow("preview")
cv2.imshow("preview", img)
You must use cv2.waitKey(0)
after cv2.imshow("window",img)
. Only then will it work.
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
If you are running inside a Python console, do this:
img = cv2.imread("yourimage.jpg")
cv2.imshow("img", img); cv2.waitKey(0); cv2.destroyAllWindows()
Then if you press Enter on the image, it will successfully close the image and you can proceed running other commands.
I faced the same issue. I tried to read an image from IDLE and tried to display it using cv2.imshow()
, but the display window freezes and shows pythonw.exe
is not responding when trying to close the window.
The post below gives a possible explanation for why this is happening
pythonw.exe is not responding
"Basically, don't do this from IDLE. Write a script and run it from the shell or the script directly if in windows, by naming it with a .pyw extension and double clicking it. There is apparently a conflict between IDLE's own event loop and the ones from GUI toolkits."
When I used imshow()
in a script and execute it rather than running it directly over IDLE, it worked.
add cv2.waitKey(0)
in the end.
Method 1:
The following code worked for me. Just adding the destroyAllWindows() didn't close the window. Adding another cv2.waitKey(1) at the end did the job.
im = cv2.imread("./input.jpg")
cv2.imshow("image", im)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
credit : https://stackoverflow.com/a/50091712/8109630
Note for beginners:
Method 2:
If you want to display on the Jupyter notebook.
from matplotlib import pyplot as plt
import cv2
im = cv2.imread("./input.jpg")
color = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
plt.imshow(color)
plt.title('Image')
plt.show()
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