Reputation: 346
I have recently installed opencv 2.4.9 and python on raspberry pi with Debian OS. I have written following simple code to display image
import numpy as np
import cv2
print "hello"
cv2.namedWindow("show",0)
print "hello1"
# Load an color image in grayscale
img = cv2.imread('image.jpg',0)
print "hellp"
cv2.imshow("show",img)
cv2.waitKey(100)
cv2.destroyAllWindows()
I am using python 2 IDLE. When I run the program only hello is printed. Also "show" window is not created. I have already tried other answers like "adding waitKey() or creating window. However none worked in my case
I am very new to Raspberry and python. may I know what is wrong in above code? Also why "hello1" is not printed ?
**EDIT*
As imshow method was not working, I tried matplotlib. However, now window frame is not getting updated
import numpy as np
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
print "new frame"
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#cv2.imwrite("framenew.jpg",frame)
# Display the resulting frame
plt.imshow(gray,cmap ='gray')
plt.show()
if cv2.waitKey(0) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
May I know how to correctly use this library
Upvotes: 1
Views: 8098
Reputation: 11
To show and update your OpenCV Window, only change this line in your update code:
if cv2.waitKey(1) & 0xFF == ord('q'): break
Upvotes: 1
Reputation: 8626
You may set the key waiting time to 0
second as waitKey(0)
. Your code waitKey(100)
instructs OpenCV to wait for 100 milliseconds then destroy the window. If you set waitKey(5000)
for 5 seconds, it will show the image for 5 seconds and destroy it.
Below is the relevant OpenCV Doc.
The function waitKey waits for a key event infinitely (when delay <= 0 ) or for delay milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is running on your computer at that time. It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.
Below is a sample usage of the waitKey() that will wait forever for Q being pressed before destroy the imshow()
window.
if cv2.waitKey(0) & 0xFF == ord('q'):
break
Hope this help.
Upvotes: 3