I have tried to place two cameras to be able to take snapshots in both, I have even put a button to activate one and then the other but one way or another whenever I activate both together or deactivate one and activate the next one the window freezes. I attach the code that I was building if you have any suggestions on the matter I would greatly appreciate it. I have little knowledge of Python in general so keep it a little friendly.
from tkinter import *
from tkinter import Tk, Label, Frame, Entry, Button
from tkinter import ttk
from PIL import Image
from PIL import ImageTk
import cv2
import threading
import imutils
window0= Tk() #Pantalla inicial
window0.title('Detección del punto optimo de vacunación') #Titulo de la ventana
window0.geometry('1280x720') #Dimesiones de la ventana
window0.configure(bg='#35455d') #Color de fondo
tabControl = ttk.Notebook(window0)
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
tabControl.add(tab1, text ='Formulario')
tabControl.add(tab2, text ='Captura de webcam')
tabControl.pack(expand = 1, fill ="both")
#Pestaña 1
label_0 = Label(tab1, text="Formulario de Registro",width=20,font=("bold", 20))
label_0.place(x=90,y=53)
label_1 = Label(tab1, text="Edad",width=20,font=("bold", 10))
label_1.place(x=70,y=130)
entry_1 = Entry(tab1)
entry_1.place(x=240,y=130)
label_2 = Label(tab1, text="Genero",width=20,font=("bold", 10))
label_2.place(x=70,y=180)
var = IntVar()
Radiobutton(tab1, text="M",padx = 5, variable=var, value=1).place(x=235,y=180)
Radiobutton(tab1, text="F",padx = 20, variable=var, value=2).place(x=290,y=180)
def IMC():
try:
peso = int(entrada_texto.get())
estatura = int(entrada2_texto.get())
imc = peso/estatura**2
etiqueta5.config(text=imc)
except ValueError:
etiqueta5.config(text="Introduce un numero")
label_3 = Label(tab1, text="Estatura",width=20,font=("bold", 10))
label_3.place(x=70,y=230)
estatura= ""
entry_3 = Entry(tab1, textvariable=estatura)
entry_3.place(x=240,y=230)
label_4 = Label(tab1,text="Peso",width=20,font=("bold", 10))
label_4.place(x=70,y=280)
peso= ""
entry_4 =Entry(tab1, textvariable=peso)
entry_4.place(x=240,y=280)
# print('Su IMC es:¨{}'.format(indice))
label_5 = Label(tab1,text="IMC:",width=20,font=("bold", 10))
label_5.place(x=70,y=330)
entry_5 =Entry(tab1)
entry_5.place(x=240,y=330)
Button(tab1, text='Capturar Imagen',width=20,bg='brown',fg='white').place(x=580,y=560)
# it is use for display the registration form on the window
def iniciarcam1():
global cap
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
visualizar()
def iniciarcam2():
global cap1
cap1 = cv2.VideoCapture(0,cv2.CAP_DSHOW)
visualizar1()
def visualizar():
global cap
if cap is not None:
ret, frame = cap.read()
if ret == True:
frame = imutils.resize(frame, width=360)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
im = Image.fromarray(frame)
img = ImageTk.PhotoImage(image=im)
lblVideo.configure(image=img)
lblVideo.image = img
lblVideo.after(20, visualizar)
else:
lblVideo.image = ""
cap.release()
def visualizar1():
global cap1
if cap1 is not None:
ret, frame = cap1.read()
if ret == True:
frame = imutils.resize(frame, width=360)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
im = Image.fromarray(frame)
img = ImageTk.PhotoImage(image=im)
lblVideo1.configure(image=img)
lblVideo1.image = img
lblVideo1.after(20, visualizar)
else:
lblVideo1.image = ""
cap1.release()
def finalizarcam1():
global cap
if cap.isOpened():cap.release()
print("Camara 1 release")
def finalizarcam2():
global cap1
if cap1.isOpened():cap1.release()
print("Camara 2 release")
cap = None
cap1 = None
btnIniciar = Button(tab1, text="Iniciar CAM1", width=20, command=iniciarcam1)
# btnIniciar.grid(column=0, row=0, padx=5, pady=5)
btnIniciar.place(x=800,y=53)
btnFinalizar = Button(tab1, text="Finalizar CAM1", width=20, command=finalizarcam1)
# btnFinalizar.grid(column=1, row=0, padx=5, pady=5)
btnFinalizar.place(x=800,y=103)
btnIniciar = Button(tab1, text="Iniciar CAM2", width=20, command=iniciarcam2)
# btnIniciar.grid(column=0, row=0, padx=5, pady=5)
btnIniciar.place(x=1000,y=53)
btnFinalizar = Button(tab1, text="Finalizar CAM2", width=20, command=finalizarcam2)
# btnFinalizar.grid(column=1, row=0, padx=5, pady=5)
btnFinalizar.place(x=1000,y=103)
lblVideo = Label(window0)
lblVideo1 = Label(window0)
# lblVideo.grid(column=0, row=1, columnspan=2)
lblVideo.place(x=500,y=200)
lblVideo1.place(x=900,y=200)
#Pestaña 2
label2_0 = Label(tab2, text="Procesado",width=20,font=("bold", 20))
label2_0.place(x=90,y=20)
window0.mainloop()
I run code and it never freeze window.
The only mistake which I found is: you fogot 1 in word visualizar1 in line lblVideo1.after(20, visualizar) in function visualizar1 - so when you start second camera then after tries to run code for first camera and it can't update image for second camera and it may look like it freeze.
Related
What I'm trying to do is to display the image cover from a flac file like in the pic below (this one is hard coded).
I ripped the cover with the function getCoverFlac from my code, but the problem begins when I try to update this img with my imgSet fucntion, the image to load exist(can see it in the dir and can even be used hard coded), but the image wont appear in the Ttkinter window. I believe its receiving the right file name since it returns the name correctly:
name of cover to display:Shikao Suga - Yuudachi ('99 NHK Hall 0 Live).flacCover.jpg
so how can I fix this?
full code bellow:
import pygame
import tkinter as tkr
from tkinter.filedialog import askdirectory
from tkinter import *
import os
from mutagen.flac import FLAC, Picture
import os.path
from PIL import ImageTk, Image
music_player = tkr.Tk()
cont = 0
music_player.title("My Music Player")
music_player.geometry("600x600")
play_list = tkr.Listbox(music_player, font="Helvetica 12 bold", bg='yellow', selectmode=tkr.SINGLE)
pygame.init()
pygame.mixer.init()
def play():
pygame.mixer.music.load(play_list.get(tkr.ACTIVE))
#gets and set the var name
var.set(play_list.get(tkr.ACTIVE))
#gets the cover and sets the the img that will be in panel
getThecover = getCoverFlac(play_list.get(tkr.ACTIVE))
imgSet(getThecover)
pygame.mixer.music.play()
def stop():
pygame.mixer.music.stop()
def pause():
pygame.mixer.music.pause()
def unpause():
pygame.mixer.music.unpause()
def selectDir():
directory = askdirectory()
os.chdir(directory)
song_list = os.listdir()
for item in song_list:
pos = 0
play_list.insert(pos, item)
pos += 1
def getCoverFlac(flac_file):
#this fucntion extracts the image from the flac file and saves it in the dir where the flac file is.
flacObj = FLAC(flac_file)
coverArt = flacObj.pictures
coverName = str(flac_file)+"Cover.jpg"
if os.path.isfile(coverName):
print(coverName+" already exists")
else:
for img in coverArt:
if img.type == 3:
with open(coverName, "wb") as f:
f.write(img.data)
print(coverName+" created and saved")
#img.show()
return coverName
def imgSet(var):
#sets the global var "img" to var
global img
print("name of cover to display:"+var)
resizeImg(var)
img = ImageTk.PhotoImage(Image.open(var))
def resizeImg(imgName):
basewidth = 300
img = Image.open(imgName)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save(imgName)
Button1 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="PLAY", command=play, bg="blue", fg="white")
Button2 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="STOP", command=stop, bg="red", fg="white")
Button3 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="PAUSE", command=pause, bg="purple", fg="white")
Button4 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="UNPAUSE", command=unpause, bg="orange", fg="white")
Button5 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="Music Dir", command=selectDir, bg="green", fg="white")
var = tkr.StringVar()
song_title = tkr.Label(music_player, font="Helvetica 12 bold", textvariable=var)
resizeImg('Haddaway - What Is Love (70 Mix).flacCover.jpg')
img = ImageTk.PhotoImage(Image.open('Haddaway - What Is Love (70 Mix).flacCover.jpg'))
panel = tkr.Label(music_player, image = img, justify=CENTER)
song_title.pack()
panel.pack(fill="x")
Button1.pack(fill="x")
Button2.pack(fill="x")
Button3.pack(fill="x")
Button4.pack(fill="x")
Button5.pack(fill="x")
play_list.pack(fill="both", expand="yes")
music_player.mainloop()
You just update the global variable img inside imageSet(), but forget to update the image of the label using panel.config(image=img):
def imgSet(var):
#sets the global var "img" to var
global img
print("name of cover to display:"+var)
resizeImg(var)
img = ImageTk.PhotoImage(Image.open(var))
panel.config(image=img) # update image of label "panel"
I recently started using opencv with tkinter, and I started to have some problems that I can't seem to fix by myself...
The following code is supposed to play a video file while being able to choose which sub-directory you want to sort the file in. The problems I started to have is that the number of frames per seconds seems to act weird, since some clip I play seems "lagging", or don't have the right fps.
Secondly, the code seems really messy, and thus buttons "disappear" after clicking on one for a moment.
And finally, I tried to do something so the buttons get as big as possible to fill the x axis on the bottom of the window, while the main frame, with the video playing, stays the same same size (so the video is supposed to stay in the middle, adapting his height and width to the frame size without changing the ratio) but that doesn't seems to work too.
Any help will be appreciated
PS: I am using Python 3.8 with openCV 4.1.2
Here is the code :
from tkinter import Tk, Button, Label, Frame
import os
import shutil
import cv2
from PIL import Image, ImageTk
x = 0
path = "path/to/folder"
def nbr():
global x
x += 1
text.config(text=files[x])
class ButtonX (Button):
def __init__ (self, *args, folder="", **kwargs):
super().__init__(*args, **kwargs)
self.folder = folder
self.config(command=self.moveTo)
def moveTo(self):
global x
global cap
global width
if cap.isOpened():
cap.release()
shutil.move(path + files[x], path + self.folder + "/" +files[x])
print(files[x] + " moved to " + self.folder)
nbr()
cap = cv2.VideoCapture(path+files[x])
ret, frame = cap.read()
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)*(height/cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
folders = [dI for dI in os.listdir(path) if os.path.isdir(os.path.join(path,dI))]
allfiles = os.listdir(path)
files = [ fname for fname in allfiles if fname.endswith('.webm')]
files.sort(key=len)
print(folders)
window = Tk()
window.resizable(0, 0)
window.geometry("1600x908")
back = Frame(window)
back.grid(row=1, column=1)
window.grid_rowconfigure(0, weight=1)
window.grid_rowconfigure(2, weight=1)
window.grid_columnconfigure(0, weight=1)
window.grid_columnconfigure(2, weight=1)
player = Frame(back)
player.grid(row = 0, column=0)
buttouns = Frame(back)
buttouns.grid(row = 1, column=0)
text = Label(player)
text.grid(row=0, columnspan=4, sticky='w,e,n,s', padx=5, pady=50)
cap = cv2.VideoCapture(path+files[x])
fps = cap.get(cv2.CAP_PROP_FPS)
cap.set(cv2.CAP_PROP_FPS, fps)
print(fps)
height = 600
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)*(height/cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
def show_frame():
global cap
global width
cap.set(cv2.CAP_PROP_FPS, fps)
ret, frame = cap.read()
if frame is None:
cap = cv2.VideoCapture(path+files[x])
ret, frame = cap.read()
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image).resize((width, height))
imgtk = ImageTk.PhotoImage(image = img)
text.imgtk = imgtk
text.configure(image=imgtk)
text.after(3, show_frame)
buttons = []
z = 1
y = 0
for i in range(len(folders)):
new_button = ButtonX(buttouns,text=folders[i], width=20, height=2, folder=folders[i])
buttons.append(new_button)
buttons[i].grid(row=z, column=y, sticky='w,e,n,s', padx=5, pady=5)
y += 1
if y == 4:
y = 0
z += 1
def deleted():
global cap
global width
print("deleted " + files[x])
if cap.isOpened():
cap.release()
shutil.move(path + files[x], "path/to/deleted" + files[x])
nbr()
cap = cv2.VideoCapture(path+files[x])
ret, frame = cap.read()
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)*(height/cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
def skipped():
global cap
global width
print(files[x] + " skipped")
if cap.isOpened():
cap.release()
nbr()
cap = cv2.VideoCapture(path+files[x])
ret, frame = cap.read()
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)*(height/cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
delete= Button(buttouns,text="Delete", width=20, height=2, command=deleted, foreground="red")
delete.grid(row=z+1,column=2, columnspan=2, sticky='w,e,n,s', padx=5, pady=5)
skip= Button(buttouns,text="Skip", width=20, height=2, command=skipped)
skip.grid(row=z+1, columnspan=2, sticky='w,e,n,s', padx=5, pady=5)
show_frame()
window.mainloop()
I want to print the mean, height & width of an image in python openCV. Where i used two button (get photo and analysis image) and different GUI,one for getting the photo(def openphoto(): ) and another for printing those features(def feature(): ). But I'm getting error.
N.B. full code is too long.so, i used some part of it.
I've tried it in python openCV.
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title("Dr. Papaya")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print here
print("Mean : ",mean)
print("Heigth : ",heigth)
print("Width : ",width)
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
load = Image.open(fileName)
#calculate the mean
mean=np.mean(load)
#calculate the height & width
height = np.size(load, 0)
width = np.size(load, 1)
render = ImageTk.PhotoImage(load)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
The variables are not in scope when you try to print them. This is an important programming principle so I suggest you read this introduction
You can make the variable global to make the them accessible outside of the function:
def openphoto():
global width, height, mean
[rest of code]
I'm new in GUI developing.Here i'hv created two GUI, one for taking photo and another for showing features.so,i'hv used two functions.but i don't know some things.Now i need two kinds of help from you.
1)what is the command for printing float value in GUI(not on console)?
2)How to calculate the value of mean,variance ,s.d. etc from a image and how to pass those values from one function to another function?
import tkinter as tk
from tkinter.filedialog
import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print some features of image e.g. Mean, variance,s.d. Etc.
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
dirPath = " "
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
#this is the image
Photo = Image.open(fileName)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
Okay, I took some more time to look into it.
Concerning the calculation of the values, your previous question did that correct, however the variables needed to be accessible globally. Concerning the displaying of a text, you have to add a tkinter text widget. If you want to add more calculated values, just google for numpy + 'value your want'.
I've taken your code and created a working example, see the code below. Note that I removed some stuff that wasn't neede for the example, so copy the lines you need to your own code. Also check out this reference for the text widget.
Result:
Code:
Note: I created 2 text widgets deliberately, to show 2 ways of implementing multiple texts
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
### create a text widget, place it in window1 and insert the text
width_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
width_txt.grid(column=0, row=0)
width_txt.insert(tk.END, "Width: " + str(width))
height_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
height_txt.grid(column=0, row=1)
height_txt.insert(tk.END, "Height: " + str(height) + "\nMean: " + str(mean))
window1.geometry("650x510")
window1.configure(background="lightgreen")
def openphoto():
### this line makes the variables accessible everywhere
global width,height, mean
import numpy as np
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
photo = Image.open(fileName)
#### calculate values
height = np.size(photo, 0)
width = np.size(photo, 1)
mean = np.mean(photo)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
I would like to open images from 2 different folders and display them next to each other , also have a button " Next" to be able to move to the next pair of images.
The images paths are stored in a txt file , so lets say open the first image and the second image and when I click next , 3rd and 4th image and so on
I am new to python and this is what I found so far to read an image
from Tkinter import *
from PIL import ImageTk, Image
import os
root = Tk()
img = ImageTk.PhotoImage(Image.open("path.ppm"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
But i can't figure how to open 2 images simultaneously and add the next button
Here is a working example of what you ask:
from tkinter import *
def UpdateImg ( ):
global img1, img2
img1 = PhotoImage(file=ImgFiles[Cur])
img2 = PhotoImage(file=ImgFiles[Cur+1])
LblImg1.configure(image = img1, text=ImgFiles[Cur])
LblImg2.configure(image = img2, text=ImgFiles[Cur+1] )
def BtnNext( ):
global Cur
if Cur < len(ImgFiles)-2:
Cur = Cur + 2
UpdateImg ( )
def BtnPrev( ):
global Cur
if Cur > 1:
Cur = Cur - 2
UpdateImg ( )
fp = open("ImgFilesSrc.txt", "r")
ImgFiles = fp.read().split('\n')
fp.close()
Cur = 0
img1 = img2 = ''
root = Tk()
#Create the main Frame -----------------------------------------------------------------
FrmMain = Frame(root)
LblImg1 = Label(FrmMain, text = "Picture 1", anchor=W, width=120, bg="light sky blue")
LblImg2 = Label(FrmMain, text = "Picture 2", anchor=W, width=120, bg="light sky blue")
BtnPrev = Button(FrmMain, text=" < ", width=10, command=BtnPrev)
BtnNext = Button(FrmMain, text=" > ", width=10, command=BtnNext)
LblImg1.grid (row=2, rowspan = 3, column=1, columnspan=3);
LblImg2.grid (row=2, rowspan = 3, column=4, columnspan=3);
BtnPrev.grid (row=5, column=2); BtnNext.grid(row=5, column=4)
FrmMain.pack(side=TOP, fill=X)
#--------------------------------------------------------------------------
UpdateImg ( )
root.mainloop()