imshow create new windows with opencv on ubuntu - python

I tried to show images from camera using cv2.imshow, but instead of updating it creates new windows.
This is the code
import cv2
if __name__ == '__main__':
roi_width = 300
roi_height = 300
cam = cv2.VideoCapture(0)
while True:
ret, original = cam.read()
roi = original[0:roi_height, 0:roi_width]
cv2.rectangle(original, (0, 0), (roi_width+5, roi_height+5), 5)
cv2.imshow("original", original)
cv2.imshow("roi", roi)
k = cv2.waitKey(1)
if k == ord('q'):
break
cv2.destroyAllWindows()
This is the result I got after 10 iterations

Related

Show another image while showing one image in loop in opencv python

I am trying to show an image, named "Result", And if a person clicks on the image then, it should show another image, named "Result image", but after clicking, the image Result which has to be live input from webcam freezes. Can anyone help me with this ?
Here is my code :
import cv2
cap = cv2.VideoCapture(0)
def showImage(event,x,y,flags,param):
if event == 1:
cv2.imshow('Result Image', img)
cv2.namedWindow('Result')
cv2.setMouseCallback('Result', showImage)
while True:
_, img = cap.read()
cv2.imshow('Result', img)
cv2.waitKey(1)
I have tried to set the waitKey(1) if the image is clicked in the if event == 1 statement
This code worked for me:
import cv2
def showImage(event,x,y,flags,param):
if event == 1:
cv2.imshow('Result Image', img)
cv2.namedWindow('Result')
cv2.setMouseCallback('Result', showImage)
cv2.namedWindow('Result Image')
cap = cv2.VideoCapture(0)
while True:
_, img = cap.read()
cv2.imshow('Result', img)
if cv2.waitKey(1) != -1: break
cv2.destroyAllWindows()

OpenCV When face not detected in live feed, exit

So I am trying to make a code where when face is detected from webcam it shows a green square around face. That part is done. What I want to make next is that when face is no longer detected by program that it break the loop and exit program. I tried ways through "if" or "else" or find something online but I was not going anywhere. Is there some way to do it? Here is my code:
import cv2
import os
import time
cascPath = os.path.dirname(
cv2.__file__) + "/data/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(60, 60),
flags=cv2.CASCADE_SCALE_IMAGE)
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h),(0,255,0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
How about adding this? Count the number of times no face is detected; break if passes a threshold:
iter_with_no_faces=0 #put this outside the main loop
### put the follwing after updating `faces`
if len(faces) ==0:
iter_with_no_faces+=1
## add break condition as this:
if iter_with_no_faces >100:
break
you can iter_with_no_faces in the faces loop: iter_with_no_faces=0
In sum, this might work with slight modification:
import cv2
import os
import time
cascPath = os.path.dirname(
cv2.__file__) + "/data/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
iter_with_no_faces=0 #put this outside the main loop
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(60, 60),
flags=cv2.CASCADE_SCALE_IMAGE)
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h),(0,255,0), 2)
if len(faces) ==0:
iter_with_no_faces+=1
else:
iter_with_no_faces=0 # I assume you want to continue program when a face detected for a duration. you can omit else statement
if iter_with_no_faces >100: #set this threshold to larger or smaller number
break
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
import cv2
def main():
cascPath = './haarcascade_frontalface_alt2.xml' # path to the xml file - change to your path
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
for i in range(10 ** 10):
ret, frame = video_capture.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(60, 60),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(faces) > 0:
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Video', frame)
k = cv2.waitKey(1)
if k == ord('q'):
break
else:
print('No face detected on iter {}'.format(i))
# add here break or whatever you want to do if no face detected
video_capture.release()
cv2.destroyAllWindows()
return
if __name__ == '__main__':
main()

failing to play the whole video using cv2

i am trying to play a video using cv2 but it's only showing one frame and the video disappears
import cv2
img_file = 'car image.jpg'
video = cv2.VideoCapture('Tesla Dashcam AccidentTrim.mp4')
while True:
(read_successful, frame) = video.read()
if read_successful:
grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
break
classifier_file = 'car_detector.xml'
#Display the image with the faces spotted
cv2.imshow('Newton Caffrey Face Detector', grayscaled_frame)
#Don't Autoclose here (wait here in the code and listen for a key press)
cv2.waitKey(1)
I used the following code for displaying the video using cv2. It will keep displaying frames untill video ends. hope this will work for you, peace!
import cv2
cap = cv2.VideoCapture("Video.mp4")
width = 400
height = 300
num = 0
while True:
ret, frame = cap.read()
if ret:
frame = cv2.resize (frame, (width, height))
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xff == ord('q'):
break
cv2.destroyAllWindows()

OpenCV python process dead

.
I am using anaconda 4.8.3, spyder 4.1.3 and opencv-python 4.2.0.34.
When I am trying to read simple image, then the python process is suspend. when I am trying to read the video there is the same problem. After each run of program I must restart the kernel.
my code for image:
import cv2
img = cv2.imread("lena.png")
cv2.imshow("Output",img)
cv2.waitKey(0)
my code for video:
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("test.mp4")
while True:
success, img = cap.read()
img = cv2.resize(img, (frameWidth, frameHeight))
cv2.imshow("Result", img)
if cv2.waitKey(1) and 0xFF == ord('q'):
break
The video and image are in the same folder as project.
Have you got any idea why this is happening?
Thanks for help.
Code for Image
import cv2
img = cv2.imread("lena.png")
cv2.imshow("Output",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Code for video
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("test.mp4")
while True:
success, img = cap.read()
img = cv2.resize(img, (frameWidth, frameHeight))
cv2.imshow("Result", img)
if cv2.waitKey(1) and 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

OpenCV putText does not work after flipping the image

I'd like to grab images from the camera and flip them left/right so that the view performs like a mirror. However, I also like to add some text to the view, but it turns out that after flipping the image using np.fliplr(frame), cv.putText does no longer work.
Here is my minimal example using python 3.5.2:
import numpy as np
import cv2
import platform
if __name__ == "__main__":
print("python version:", platform.python_version())
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.putText(frame,'Hello World : Before flip',(100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
frame = np.fliplr(frame)
cv2.putText(frame,'Hello World : After flip',(100, 200), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
# Process the keys
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
print("quit")
break
# show the images
cv2.imshow('frame',frame)
cap.release()
cv2.destroyAllWindows()
Resulting frame w/ flip:
Resulting frame w/o flip:
I suspect it's due to cv2.putText is not compatible with np.array which is the return value of np.fliplr(frame). I suggest that you use frame = cv2.flip(frame, 1) instead.
import numpy as np
import cv2
import platform
if __name__ == "__main__":
print("python version:", platform.python_version())
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.putText(frame,'Hello World : Before flip',(100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
frame = cv2.flip(frame, 1)
cv2.putText(frame,'Hello World : After flip',(100, 200), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2,cv2.LINE_AA)
# Process the keys
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
print("quit")
break
# show the images
cv2.imshow('frame',frame)
cap.release()
cv2.destroyAllWindows()
Just flip the frame before putting the text:
frame = cv2.flip(frame, 1)
cv2.putText(...)

Categories