How to display an image and a terminal in OpenCV - python

How can use OpenCV to display my webcam and a terminal at the same time? I need the terminal to run some commands to make the webcam appear and others different actions with the object detection.

Here's a very simple example of running a webcam while at the same time being able to use terminal input() by doing all the opencv frame capturing, and imshowing from a separate thread:
from threading import Thread
import cv2
shouldExit = False
color = True
def cam():
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while not shouldExit:
ret, frame = cap.read()
if not color:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("window title", frame)
cv2.waitKey(1)
cap.release()
cv2.destroyAllWindows()
t = Thread(target=cam)
t.start()
while True:
print('select an action: q-quit, t-toggle color')
choice = input(">").strip().lower()
if choice == 'q':
shouldExit = True
t.join()
break
elif choice == 't':
color = not color
else:
print('invalid input')

Related

How to play it on fullscreen python cv2

How do I play the video.mp4 in fullscreen instead of playing it in a window
and is there any way to play video with audio without playing the audio separately?
import cv2
from playsound import playsound
from threading import Thread
def func1():
cap = cv2.VideoCapture("video.mp4")
ret, frame = cap.read()
while(1):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(33) & 0xFF == ord('q') or ret==False :
cap.release()
cv2.destroyAllWindows()
break
cv2.imshow('frame',frame)
def func2():
playsound('6989946141014084358.mp3')
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
You should be able to setup the window ahead of time (e.g. before your blocking while loop):
cv2.namedWindow('frame',cv2.WINDOW_NORMAL)
cv2.setWindowProperty('frame',cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)

Computer Terminating OpenCv Image Grabber Program

I Have Created a Program in Python in which it uses opencv to grab some images and save it.I have runned this program on my mac and it works fine does what i expect but on my computer the webcam feed shows and the first image when i click space works but when i click for the second time to grab images it doesnt works.The following is the error message that it shows
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-hfoi92lm\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Below is my code
import cv2
import subprocess
from sys import exit
import os
# Code!
import time
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
cv2.startWindowThread()
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
cv2.imshow("test", frame)
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
# SPACE pressed
img_name = f'\\Users\\Anush\\PycharmProjects\\PelletInspection\\Sample_Images\\Sample_Image_{img_counter}.jpg'
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()
try to comment #cv2.startWindowThread()
try editing cv2.waitKey(33) instead of cv2.waitKey(1)

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()

uninterrupted while loop with python cv2.VideoCapture() and string input

I use this code to capture and display the input from my webcam.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
check, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I have a barcode scanner and want to check inside the while loop if a specific string gets scanned in.
input() interupts the stream from the webcam. I need something like cv2.waitKey() but for strings
while(True):
check, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitString(barcode) == '123456':
# do something
if cv2.waitString(barcode) == '098765':
# do something else
I tried msvcrt, but to no avail. The stream continues but nothing gets printed.
if msvcrt.kbhit():
if msvcrt.getwche() == '280602017300':
print("Barcode scanned!")
Or is there a way to skip input() until something was entered?
UPDATE
Making some progress with the help of this post.
How to read keyboard-input?
I was able to update my code.
import threading
import queue
import time
import numpy as np
import cv2
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
input_str = input()
inputQueue.put(input_str)
def main():
inputQueue = queue.Queue()
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_DUPLEX
fontScale = 1
fontColor = (255,255,255)
lineType = 2
input_str = "test"
while (True):
check, frame = cap.read()
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
if (input_str == '280602017300'):
print("do something")
cv2.putText(frame, input_str, (10,30), font, fontScale, fontColor, lineType)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
time.sleep(0.01)
print("End.")
if (__name__ == '__main__'):
main()
Now the only problem left is that my webcam stream is supposed to run in fullscreen. So the console will allways be in the background and therefore wont get the inputs form the keyboard or my barcode scanner.
need it the other way around

Cannot Close Video Window in OpenCV

I would like to play a video in openCV using python and close that window at any time, but it is not working.
import numpy as np
import cv2
fileName='test.mp4' # change the file name if needed
cap = cv2.VideoCapture(fileName) # load the video
while(cap.isOpened()):
# play the video by reading frame by frame
ret, frame = cap.read()
if ret==True:
# optional: do some image processing here
cv2.imshow('frame',frame) # show the video
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
The window opens and starts playing the video, but I cannot close the window.
You can use cv2.getWindowProperty('window-name', index) to detect if the window is closed. I'm not totally sure about the index but this worked for me:
import cv2
filename = 'test.mp4'
cam = cv2.VideoCapture(filename)
while True:
ret, frame = cam.read()
if not ret:
break
cv2.imshow('asd', frame)
cv2.waitKey(1)
if cv2.getWindowProperty('asd', 4) < 1:
break

Categories