how to hide the title bar or window in python - python

i want to hide my window or tittle bar of my window. as i want to show the output of the opencv frameless.
tell me how can i do that with the help of tkinter or pyqt5.
and also i want the size of the output according to my specation.
and can i resize and change the place of the output like drag and drop anywhere on desktop while the code is running.
import cv2
import os
import numpy as np
import datetime
date=datetime.datetime.now()
framerate=24
screen_size=(640,480) #std res 640,480
filename='E:/project/videos/cam_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
cap=cv2.VideoCapture(0)
out= cv2.VideoWriter(filename,fourcc,framerate,screen_size)
cv2.namedWindow('frame',cv2.WINDOW_NORMAL)
cv2.resizeWindow('frame',280,190)
cv2.moveWindow('frame',5,495)
#cv2.namedWindow('frame',cv2.WND_PROP_FULLSCREEN) #use for full screen
#cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame=cv2.flip(frame,1)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
screen.mainloop()

Below is an example using tkinter to show the capture images from webcam:
import cv2
import datetime
from tkinter import *
from PIL import Image, ImageTk
screen = Tk()
screen.overrideredirect(1) # remove window decorations
screen.geometry('280x200+5+520') # move the window
framerate = 24
screen_size = (640, 480) #std res 640,480
date = datetime.datetime.now()
filename = 'E:/project/videos/cam_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
date.hour, date.minute, date.second)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(filename, fourcc, framerate, screen_size)
cap = cv2.VideoCapture(0)
imgbox = Label(screen)
imgbox.pack(fill=BOTH, expand=1)
def quit(event):
cap.release()
out.release()
screen.destroy()
def read_frame():
ret, frame = cap.read()
if ret:
frame = cv2.flip(frame, 1)
out.write(frame)
# since openCV capture image is in BGR color sequence
# so need to convert it to RGB color sequence
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# convert the openCV image to PIL (Pillow) format
img = Image.fromarray(frame)
#img = img.resize((280, 200)) # not keep aspect ratio
img.thumbnail((280, 200)) # keep aspect ratio
img = ImageTk.PhotoImage(img)
imgbox.config(image=img) # update the image
img.image = img # keep a reference of the image to avoid being garbage collected
screen.after(20, read_frame) # schedule next read after 20 ms
# bind the 'q' key to quit program
screen.bind('q', quit)
read_frame()
screen.mainloop()

Related

How to display an image from OpenCV in a Tkinter interface?

I am trying to continuously display and replace an image in a Tkinter interface taken from OpenCV's VideoCapture. However, I am getting the following error that I think is a result of improper formatting of the image numpy array:
TypeError: unhashable type: 'numpy.ndarray'
How can I reformat it to all it to display properly? Below is my code:
import tkinter as tk
import cv2
import numpy as np
from PIL import ImageTk, Image
main = tk.Tk()
main.title("Hole Pattern Recognition")
main.geometry("300x300")
frame = tk.Frame(main)
frame.pack()
def startScan():
global main, frame
#begins utilizing webcam for scan
cap = cv2.VideoCapture(0)
while(True):
ret,img = cap.read()
img = ImageTk.PhotoImage(img)
panel = tk.Label(main, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
ch = cv2.waitKey(1)
if ch == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
startButton = tk.Button(frame,
text="Start Scan",
fg="blue",
command=startScan)
startButton.pack(side=tk.TOP)
main.mainloop()
First you need to use PIL.Image.fromarray() to convert the captured image to format supported by tkinter.
Second better not use while loop in main thread as it will block the tkinter mainloop. Use after() instead.
import tkinter as tk
from PIL import Image, ImageTk
import cv2
cap = None
main = tk.Tk()
main.title('Hole Pattern Recognition')
#main.geometry('300x300')
frame = tk.Frame(main)
frame.pack()
def startScan():
global cap
def scan():
ret, img = cap.read()
if ret:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
tkimg = ImageTk.PhotoImage(img)
panel.config(image=tkimg)
panel.tkimg = tkimg # save a reference to the image to avoid garbage collection
panel.after(25, scan) # change 25 to other value to adjust FPS
if cap is None:
cap = cv2.VideoCapture(0)
scan() # start the capture loop
else:
print('capture already started')
startButton = tk.Button(frame, text='Start Scan', fg='blue', command=startScan)
startButton.pack()
panel = tk.Label(main)
panel.pack()
main.mainloop()
if cap:
cap.release()

why the webcam is showing anything in opencv

I am making a gui with a button to make webcam on and off. and it is working but when i open it again after closing it then its shows only black screen.
how to resolve this issue.
Here is my code. my whole code is huge so i posted on the webcam part here.
i updated my code .......................
import tkinter as tk
from tkinter import *
import cv2
import numpy as np
from PIL import Image, ImageTk, ImageGrab
cap = cv2.VideoCapture(0)
webcam = None
WEBCAM_SIZE = (280, 200)
def read_frame(imgbox):
if cap.isOpened():
ret, frame = cap.read()
if ret:
frame = cv2.flip(frame, 1)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame, WEBCAM_SIZE)
image = Image.fromarray(frame)
imgbox.image.paste(image)
webcam.after(20, read_frame, imgbox)
def stop_webcam(event):
global webcam
if webcam:
webcam.destroy()
webcam = None
cap.release()
def start_webcam():
global webcam
cap.open()
if webcam is None:
cap.isOpened()
webcam = tk.Toplevel()
#webcam = tk.lift()
webcam.attributes("-topmost", True) #it keep the window on top of others
webcam.geometry('{}x{}+5+520'.format(WEBCAM_SIZE[0], WEBCAM_SIZE[1]))
webcam.overrideredirect(1)
imgbox = tk.Label(webcam)
imgbox.pack()
imgbox.image = ImageTk.PhotoImage(image=Image.new('RGB',WEBCAM_SIZE,(0,0,0)))
imgbox.config(image=imgbox.image)
#webcam.bind('', stop_webcam)
read_frame(imgbox)
cap_btn = ttk.Button(frame, image=web, width=20, command=change_w)
cap_btn.grid(row=0, column=2)
cap_btn.image = web
def change_w():
if cap_btn.image == web:
start_webcam()
cap_btn.config(image=web2)
cap_btn.image = web2
else:
stop_webcam(None)
cap_btn.config(image=web)
cap_btn.image = web
web = PhotoImage(file='webcam.png')
web2 = PhotoImage(file='bl.png')
root.mainloop()

Is there a way to check if camera is connected without cap = cv2.videocapture

I am making a program that checks if the camera is connected, and if so, Show the webcam footage, The problem is: The way i structured my program i cannot have cap = cv2.videocapture() for the time it takes the command to execute. This makes sabotages for the showframe function and makes it only show a frame every ~1 second. Is there a different way to check if the camera is connected rather than cap = cv2.videocapture() and cap.isOpened()?
I also cannot have a while loop in my program because of the root.mainloop command for tkinter, However, if there is no way to check my camera status rather than cap.isOpened(), can i move the root.mainloop command somewhere where i can have a while True loop in my program?
I've tried both Multiprocessesing and Threading with no further success.
Heres some code:
from tkinter import * # Import the tkinter module (For the Graphical User Interface)
import cv2 # Import the cv2 module for web camera footage
import PIL # Import the pillow library for image configuration.
from PIL import Image, ImageTk # Import the specifics for Image configuration.
print("[INFO] Imports done")
width, height = 800, 600 # Define The width and height widget for cap adjustment
RootGeometry = str(width) + "x" + str(height) # Make a variable to adjust tkinter frame
print("[INFO] Geometries made")
ImageSource = 0
cap = cv2.VideoCapture(ImageSource) # First VideoCapture
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
print("[INFO] Cap set")
root = Tk()
print("[INFO] Window made")
root.title("Main Window")
root.configure(background="white")
root.geometry(RootGeometry)
root.bind('<Escape>', lambda e: root.quit())
lmain = Label(root)
lmain.pack()
print("[INFO] Configuration of cap done.")
def ShowFrame():
ok, frame = cap.read()
if ok:
print("[INFO] Show frame Initialized.")
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = PIL.Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
print("[INFO] After 10 initializing")
lmain.after(10, ShowFrame)
print("[INFO] Showed image")
else:
lmain.after(10, CheckSource)
def CheckSource():
print("[INFO] CheckSource Triggered.")
cap = cv2.VideoCapture(ImageSource)
if cap.isOpened():
print("[INFO] [DEBUG] if Ok initialized")
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
cv2.waitKey(0)
print("[WARNING] Exiting app after command")
ShowFrame()
else:
print("[WARNING] No source found. Looking for source.")
lmain.after(10, CheckSource)
CheckSource()
root.mainloop()
print("[INFO] [DEBUG] Root.Mainoop triggered")
Any and all help would be very appreciated!
When there is no webcam/image source, cap.read() will be (False, none). Therefore you can check if a webcam is connected if you do something like:
import cv2
cap=cv2.VideoCapture(ImageSource)
while True:
if cap.read()[0]==False:
print("Not connected")
cap=cv2.VideoCapture(imageSource)
else:
ret, frame=cap.read()
cv2.imshow("webcam footage",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Hope this helps :)
You should not do a VideoCapture each frame, you only need to check if it exists. isOpened() is the proper function for that. If it does not yet exist, then retry the cam.
I modified your code:
def CheckSource():
print("[INFO] CheckSource Triggered.")
# check if cam is open, if so, do showFrame
if cap.isOpened():
print("[INFO] [DEBUG] if Ok initialized")
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
cv2.waitKey(0)
print("[WARNING] Exiting app after command")
ShowFrame()
else:
# cam is not open, try VideoCapture
print("[WARNING] No source found. Looking for source.")
cap = cv2.VideoCapture(ImageSource)
lmain.after(10, CheckSource)

Opencv and Tkinter: How can i automatically show webcam video?

I am having a problem where i cant find a way to display Opencv webcam video in a Tkinter frame, I would've used the basic code online but the problem is that i cant seem to make it automatically make a frame when the webcam is connected.
I've tried modifying the code i found online, But at this point i honestly don't have any idea of what i am doing.
import cv2
from tkinter import *
import PIL
from PIL import Image, ImageTk
root = Tk()
root.bind('<Escape>', lambda e: root.quit())
lmain = Label(root)
lmain.pack()
print("[INFO] Making variables")
ImageSource = 0
window_name = "AutoCam"
cap = cv2.VideoCapture(ImageSource)
print("[INFO] Made variables ")
def CheckSource():
print("[INFO] Checking image source")
while True:
print("[INFO] Reading frame")
cap = cv2.VideoCapture(ImageSource)
while cap.isOpened():
_, frame = cap.read()
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = PIL.Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, show_frame)
print("[INFO] cv2.imshw done")
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
cv2.waitKey(0)
break
Check_root = False
def CheckRootDef():
if Check_root:
CheckSource()
CheckRootDef()
root.mainloop()
check_root = True
CheckRootDef()
i expect it to make a costum Tkinter window and show my webcam footage live on it, And that as soon as the webcam is detected.

stream from thermal camera (ip camera) on python , connection error

i want to stream from a thermal camera, usually it export its frames as gray scale frames
the thermal camera is an IP camera , i tried different codes and package but with no output.
when i change the code a little bit to view from a USB camera it works normally, so any help please.
this is the code i have tried :
import sys
sys.path.append('C:\Python27\Lib\site-packages')
import Tkinter as tk
import cv2
from PIL import Image, ImageTk
i=0
window = tk.Tk()
window.title('thermal image')
var = tk.IntVar()
width, height = 800, 600
cap = cv2.VideoCapture(0)
cap.open("http://169.254.110.119/")
left_label = tk.Label(window)
left_label.pack(side="left")
right_label = tk.Label(window)
right_label.pack(side="right")
def show_frame():
_, frame = cap.read()
print frame
if frame != None:
frame = cv2.flip(frame, 1)
img = Image.fromarray(frame)
imgtk = ImageTk.PhotoImage(image=img)
left_label.imgtk = imgtk
left_label.configure(image=imgtk)
left_label.after(10, show_frame)
show_frame()
window.mainloop()
I think that the image from the websitre is not being grabbed in the code, what worked for me was
img_requested = requests.get(url)
img_arr = np.array(bytearray(img_requested.content), dtype=np.uint8)
frame = cv2.imdecode(img_arr, -1)
And there you would get the frame (color picures/video).Keep in mind that you need to import requests and numpy as np.
It is important if you are using IP Webcam that you do not forget to write the '/shot.jpg'
at the end of the url, like this: 'http://190.160.0.0:8080/shot.jpg', so that it effectivelly grabs the image.

Categories

Resources