I am write the code to recognition the face and mark attendence but so Error come and when i run the project the camere are open but not recogition the face the give face are stick on the camera screen.
and the following error is are has follw:
File "g:\Attendence System\face_recognition.py", line 93, in face_recog
img=recognize(img,clf,faceCascade)
File "g:\Attendence System\face_recognition.py", line 82, in recognize
coord = draw_boundray(img,faceCascade,1.1,10,(255,255,255),"Face",clf)
File "g:\Attendence System\face_recognition.py", line 59, in draw_boundray
name="+".join(name)
TypeError: can only join an iterable
and some varible i declare but It's not access the given error is ret is not accessed pylance
plz help with this problem.
from tkinter import*
from tkinter import ttk
from PIL import Image,ImageTk
from tkinter import messagebox
import mysql.connector
import cv2
import os
import numpy as np
class Face_Recognition:
def __init__(self,root):
self.root=root
self.root.geometry("1530x790+0+0")
self.root.title("Face Recognition System")
lbl_title=Label(self.root,text="FACE RECOGNITION",font=("time new roman",35,"bold"),bg="white",fg="green")
lbl_title.place(x=0,y=0,width=1530,height=45)
#1st image
img_top=Image.open(r"Images\workingonface.jpg")
img_top=img_top.resize((650,700),Image.ANTIALIAS)
self.photoimg_top=ImageTk.PhotoImage(img_top)
f_lbl=Label(self.root,image=self.photoimg_top)
f_lbl.place(x=0,y=55,width=650,height=700)
#2st image
img_bottom=Image.open(r"Images\facial_recognition_system_identi.jpg")
img_bottom=img_bottom.resize((950,700),Image.ANTIALIAS)
self.photoimg_bottom=ImageTk.PhotoImage(img_bottom)
f_lbl=Label(self.root,image=self.photoimg_bottom)
f_lbl.place(x=650,y=55,width=950,height=700)
#buttom
b1_1=Button(f_lbl,text="Face Recognition",cursor="hand2",command=self.face_recog,font=("time new roman",18,"bold"),bg="darkgreen",fg="white")
b1_1.place(x=365,y=620,width=210,height=40)
#==================Face recognition=============
def face_recog(self):
def draw_boundray(img,classifier,scaleFactor,minNeighbors,color,text,clf):
gray_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
features = classifier.detectMultiScale(gray_image,scaleFactor,minNeighbors)
coord=[]
for(x,y,w,h) in features:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
id,predict=clf.predict(gray_image[y:y+h,x:x+w])
confidence=int((100*(1-predict/300)))
con = mysql.connector.connect(host='localhost',username='root',password='',database='face_recognition')
my_courser=con.cursor()
my_courser.execute("select Name from students where StudentID="+str(id))
name=my_courser.fetchone()
name="+".join(name)
my_courser.execute("select Roll from students where StudentID="+str(id))
r=my_courser.fetchone()
r="+".join(r)
my_courser.execute("select Dep from students where StudentID="+str(id))
d=my_courser.fetchone()
d="+".join(d)
if confidence>77:
cv2.putText(img,f"Roll No:{r}",(x,y-55),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
cv2.putText(img,f"Name:{name}",(x,y-30),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
cv2.putText(img,f"Department:{d}",(x,y-5),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
else:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3)
cv2.putText(img,"Unknown face",(x,y-5),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
coord=[x,y,w,y]
return coord
def recognize(img,clf,faceCascade):
coord = draw_boundray(img,faceCascade,1.1,10,(255,255,255),"Face",clf)
return img
faceCascade=cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
clf=cv2.face.LBPHFaceRecognizer.create()
clf.read("classifier.xml")
video_cap=cv2.VideoCapture(0)
while True:
ret,img=video_cap.read()
img=recognize(img,clf,faceCascade)
cv2.imshow("Welcome To Face Recognition",img)
if cv2.waitKey(1)==13:
break
video_cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
root = Tk()
obj=Face_Recognition(root)
root.mainloop()
I guess your issue definitely is not a face recognition one:
name=my_courser.fetchone()
name="+".join(name)
Your error means that name is not iterable as it shoud be if my_courser.fetchone() returns something but None.
You may try:
name=my_courser.fetchone()
if name:
name="+".join(name)
And do the same at the next similar blocks ahead.
Related
I'm having trouble decoding an image when I import it from another file.
I have four .py files to make two buttons.
In the first, on line 21, the button works and brings the image, in the second, on line 28, which is imported from another file, it appears as a button but without an image. How can I resolve this?
lab.py
import tkinter as tk
import base64
from imagens import *
from cores import *
from widgets import *
class Janela(Images):
def __init__(self) -> None:
self.images_base64()
self.tamJanela()
def tamJanela(self):
self.janela_doMenu = tk.Tk()
janela = self.janela_doMenu
# janela.state('zoomed')
janela.title('Disk Gás Gonçalves')
janela.configure(background=preto_claro)
janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight()))
# Here the code works ###############################################################
self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))
self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',
highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')
self.rotulo_nome2.grid(row=0, column=0)
# Here the code does not work #######################################################
# I'm importing from widgets.py #####################################################
Botoes(janela)
janela.minsize(1200, 640)
janela.mainloop()
Janela()
widgets.py
import tkinter as tk
import base64
from imagens import *
from cores import *
class Botoes(Images):
def __init__(self, local) -> None:
self.images_base64()
self.local = local
self.bt()
def bt(self):
self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))
self.rotulo_nome2 = tk.Button(master=self.local, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',
highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')
self.rotulo_nome2.grid(row=1, column=0)
cores.py
preto_claro = '#4F4F4F'
verde_médio = '#00FA9A'
vermelho_salmão = '#FA8072'
azul_seleção = '#F0FFFF'
verde_limão = '#00FF00'
branco_gelo = '#EDEBE6'
imagens.py
import base64
class Images:
def images_base64(self):
self.addUser = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAFiVAABYlQHZbTfTAAAAB3RJTUUH5gkWFg4SATq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0ZGF0ZTpjcmVhdGUAMjAyMi0wOS0yMlQyMjoxNjoxNyswMDowMOu8Z3oAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjItMDktMjJUMjI6MTY6MTcrMDA6MDCa4d/GAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAABJRU5ErkJggg=='
I tried to create a button by importing the base64 image from another file.
There are two buttons in the application, one works and the image appears, the other does not work and the image does not appear. I would like to make the second one work.
All the code will generate this image. The bottom button that doesn't show the image is in the widgets.py file
I don't know why, but when I import it, it doesn't work.
Thank you in advance for your attention and I apologize if something was wrong or out of standard, my English is not very good.
It is because there is no variable referencing the instance of Botoes(), so it will be garbage collected (so as the image inside it).
Just use a variable to store the instance of Botoes():
class Janela(Images):
def __init__(self) -> None:
self.images_base64()
self.tamJanela()
def tamJanela(self):
self.janela_doMenu = tk.Tk()
janela = self.janela_doMenu
# janela.state('zoomed')
janela.title('Disk Gás Gonçalves')
janela.configure(background=preto_claro)
janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight()))
# Here the code works ###############################################################
self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))
self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',
highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')
self.rotulo_nome2.grid(row=0, column=0)
# need a variable to store the instance of Botoes
# to avoid garbage collection
botoes = Botoes(janela)
janela.minsize(1200, 640)
janela.mainloop()
Result:
Hope you are all okay. I'm working in my firts app built with tkinter in OOP. My assignment is to creaty a GUI for a supermarket. One of the windows I need to build is one that show information about a product in the stock. Including an image of the product. The way I have been working on it is to having the images of my products named with the ID number of each product. But there is a bug i can´t solve, someway the code does not reconogize the instruccion to put the image I ask in the window created with the rest of information. This is the code I´m working in. Any help or answer you could give will help me a lot. Is my first project and I haven´t sleep very well.
Sorry for programming in spanish, btw.
from tkinter import *
from tkinter import ttk
from database import productos
from PIL import Image, ImageTk
class Verproducto:
def __init__(self):
self.verproducto=Toplevel()
self.verproducto.title("Ver información del producto")
self.IDaconsultar=IntVar()
self.nombreimagen=StringVar()
self.producto = None
self.mensa=StringVar()
self.solicitudid=ttk.Label(self.verproducto, text="Ingrese el ID del producto a consultar").pack()
self.IDentry=ttk.Entry(self.verproducto, textvariable=self.IDaconsultar).pack()
self.mensaset=ttk.Label(self.verproducto, textvariable=self.mensa).pack()
self.botón=ttk.Button(self.verproducto, text="Consultar", command=self.comando).pack()
self.salir=ttk.Button(self.verproducto, text="Salir", command=self.verproducto.destroy).pack()
self.verproducto.grab_set()
def ver_informacion_producto(self):
print(True)
id=self.IDaconsultar.get()
for i in productos:
#print(i, id)
if id == i[-4]:
print(True)
self.producto = i
#self.mostrar_producto()
print(self.producto)
print(self.producto[-4])
else:
self.mensa.set("Producto no encontrado")
def mostrar_producto(self, img):
self.vistaproducto=Toplevel()
self.nombrepro=StringVar(value=self.producto[-3])
self.marcapro=StringVar(value=self.producto[-5])
self.preciopro=IntVar(value=self.producto[-2])
self.stockpro=IntVar(value=self.producto[-1])
self.vistaproducto.title(f"Producto {self.producto[-4]}")
self.nombre=ttk.Label(self.vistaproducto, text="Nombre").pack()
self.nombreshow=ttk.Label(self.vistaproducto, textvariable=self.nombrepro).pack()
self.marca=ttk.Label(self.vistaproducto, text="Marca").pack()
self.marcashow=ttk.Label(self.vistaproducto, textvariable=self.marcapro).pack()
self.precio=ttk.Label(self.vistaproducto, text="Precio").pack()
self.precioshow=ttk.Label(self.vistaproducto, textvariable=self.preciopro).pack()
self.stock=ttk.Label(self.vistaproducto, text="Stock").pack()
self.stockshow=ttk.Label(self.vistaproducto, textvariable=self.stockpro).pack()
self.foto=ttk.Label(self.vistaproducto, image=img).pack()
self.cerrar=ttk.Button(self.vistaproducto, text="Salir", command=self.vistaproducto.destroy).pack()
def imagenproducto(self):
print(self.producto)
imagen=self.producto[-4]
self.nombreimagen.set(imagen)
print(self.nombreimagen.get())
image = Image.open(f"C:\\Users\\LENOVO\\Desktop\\Python\\Pruebas TKinter\\Parcial2\\test_breigner\\img\\{self.nombreimagen.get()}.jpg")
resize_image = image.resize((200, 200))
img = ImageTk.PhotoImage(resize_image)
return img
# self.label1 = Label(image=img)
# self.label1.image = img
#self.label1.pack()
def comando(self):
self.ver_informacion_producto()
x = self.imagenproducto()
#print(x)
self.mostrar_producto(x)
strong text :
This the error of my code I don't know how to fixe it please solve it. Here i am using Python 3.7
File "c:\Users\ARAVIND SINGH\Desktop\Face Recogtion Attention System\face_recognition.py", line 105, in face_recog
img=recogize(img,clf,faceCascade)
File "c:\Users\ARAVIND SINGH\Desktop\Face Recogtion Attention System\face_recognition.py", line 94, in recogize
coord=draw_boundray(img,faceCascade,1.1,10,(255,25,255),"Face",clf)
File "c:\Users\ARAVIND SINGH\Desktop\Face Recogtion Attention System\face_recognition.py", line 69, in draw_boundray
n="+".join(n)
TypeError: can only join an iterable
strong text
Here is my code :
from tkinter import*
from tkinter import ttk
from PIL import Image,ImageTk
from tkinter import messagebox
import mysql.connector
import sqlite3
import os
import cv2
import numpy as np
import tracestack
class Face_Reconition:
def __init__(self,root):
self.root=root
self.root.geometry('1530x790-0+0')
self.root.title("Face Recogintion System")
title_label=Label(self.root,text="Face Recongition",font=('times new roman',35,"bold"),bg='white',fg="darkgreen")
title_label.place(x=0,y=0,width=1530,height=48)
# Fist image
img_top=Image.open(r"img\face_detector1.jpg")
img_top=img_top.resize((650,700),Image.ANTIALIAS)
self.photoimg_left=ImageTk.PhotoImage(img_top)
f_lbl=Label(self.root,image=self.photoimg_left)
f_lbl.place(x=0,y=50,width=650,height=700)
# Second Image
img_bottom=Image.open(r"img\ww.jpg")
img_bottom=img_bottom.resize((950,700),Image.ANTIALIAS)
self.photoimg_bottom=ImageTk.PhotoImage(img_bottom)
f_lbl=Label(self.root,image=self.photoimg_bottom)
f_lbl.place(x=650,y=50,width=950,height=700)
#Button
b1=Button(f_lbl,text="Face Reconition",cursor='hand2',command=self.face_recog,font=('time new roman',18,'bold'),bg='darkgreen',fg='white')
b1.place(x=370,y=620,width=200,height=40)
#=============Face Reconition ============== function======
def face_recog(self):
def draw_boundray(img,classifier,scalFactor,minNeighbors,color,text,clf):
gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
features=classifier.detectMultiScale(gray_image,scalFactor,minNeighbors)
coord=[]
for (x,y,w,h) in features:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
id,predict=clf.predict(gray_image[y:y+h,x:x+w])
confidence=int((100*(1-predict/300)))
conn=mysql.connector.connect(host="localhost",user="root",password="12345",database="face_recognizer")
my_cursor=conn.cursor()
my_cursor.execute("select Name from student where Student_id="+str(id))
n=my_cursor.fetchone()
n="+".join(n)
my_cursor.execute("select Roll from student where Student_id="+str(id))
r=my_cursor.fetchone()
r="+".join(r)
my_cursor.execute("select Dep from student where Student_id="+str(id))
d=my_cursor.fetchone()
d="+".join(d)
if confidence>77:
cv2.putText(img,f"Roll:{r}",(x,y-55),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
cv2.putText(img,f"Name:{n}",(x,y-30),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
cv2.putText(img,f"Department:{d}",(x,y-5),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
else:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3)
cv2.putText(img,"Unknon Face",(x,y-5),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,255,255),3)
coord=[x,y,w,h]
return coord
def recogize(img,clf,faceCascade):
coord=draw_boundray(img,faceCascade,1.1,10,(255,25,255),"Face",clf)
return img
faceCascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
clf=cv2.face.LBPHFaceRecognizer_create()
clf.read("classifier.xml")
video_cap=cv2.VideoCapture(0)
while True:
ret,img=video_cap.read()
img=recogize(img,clf,faceCascade)
cv2.imshow("Welcome to face Regonition ",img)
if cv2.waitKey(1)==13:
break
video_cap.release()
cv2.destroyAllWindows()
tracestack.pm()
if __name__=="__main__":
root=Tk()
obj=Face_Reconition(root)
root.mainloop()
Currently trying write code with a GUI which will allow for toggling on/off image processing. Ideally the code will allow for turning on/off window view, real time image processing (pretty basic), and controlling an external board.
The problem I'm having revolves around the cv2.imshow() function. A few months back I made a push to increase processing rates by switching from picamera to cv2 where I can perform more complex computations like background subtraction without having to call python all the time. using the bcm2835-v4l2 package, I was able to pull images directly from the picamera using cv2.
fast forward 6 months and while trying to update the code, I find that the function cv2.imshow() does not display correctly anymore. I thought it might be a problem with bcm2835-v4l2 but tests using matplotlib show that the connection is fine. it appears to have everything to do with cv2.imshow() or so I guess.
I am actually creating a separate thread using the threading module for image capture and I am wondering if this could be the culprit. I don't think so though as typing in the commands
import cv2
camera = cv2.VideoCapture(0)
grabbed,frame = camera.read()
cv2.imshow(frame)
produces the same black screen
Down below is my code I am using (on the RPi3) and some images show the error and what is expected.
as for reference here are the details about my system
Raspberry pi3
raspi stretch
python 3.5.1
opencv 3.4.1
Code
import cv2
from threading import Thread
import time
import numpy as np
from tkinter import Button, Label, mainloop, Tk, RIGHT
class GPIOControllersystem:
def __init__(self,OutPinOne=22, OutPinTwo=27,Objsize=30,src=0):
self.Objectsize = Objsize
# Build GUI controller
self.TK = Tk() # Place TK GUI class into self
# Variables
self.STSP = 0
self.ShutdownVar = 0
self.Abut = []
self.Bbut = []
self.Cbut = []
self.Dbut = []
# setup pi camera for aquisition
self.resolution = (640,480)
self.framerate = 60
# Video capture parameters
(w,h) = self.resolution
self.bytesPerFrame = w * h
self.Camera = cv2.VideoCapture(src)
self.fgbg = cv2.createBackgroundSubtractorMOG2()
def Testpins(self):
while True:
grabbed,frame = self.Camera.read()
frame = self.fgbg.apply(frame)
if self.ShutdownVar ==1:
break
if self.STSP == 1:
pic1, pic2 = map(np.copy,(frame,frame))
pic1[pic1 > 126] = 255
pic2[pic2 <250] = 0
frame = pic1
elif self.STSP ==1:
time.sleep(1)
cv2.imshow("Window",frame)
cv2.destroyAllWindows()
def MProcessing(self):
Thread(target=self.Testpins,args=()).start()
return self
def BuildGUI(self):
self.Abut = Button(self.TK,text = "Start/Stop System",command = self.CallbackSTSP)
self.Bbut = Button(self.TK,text = "Change Pump Speed",command = self.CallbackShutdown)
self.Cbut = Button(self.TK,text = "Shutdown System",command = self.callbackPumpSpeed)
self.Dbut = Button(self.TK,text = "Start System",command = self.MProcessing)
self.Abut.pack(padx=5,pady=10,side=RIGHT)
self.Bbut.pack(padx=5,pady=10,side=RIGHT)
self.Cbut.pack(padx=5,pady=10,side=RIGHT)
self.Dbut.pack(padx=5,pady=10,side=RIGHT)
Label(self.TK, text="Controller").pack(padx=5, pady=10, side=RIGHT)
mainloop()
def CallbackSTSP(self):
if self.STSP == 1:
self.STSP = 0
print("stop")
elif self.STSP == 0:
self.STSP = 1
print("start")
def CallbackShutdown(self):
self.ShutdownVar = 1
def callbackPumpSpeed(self):
pass
if __name__ == "__main__":
GPIOControllersystem().BuildGUI()
Using matplotlib.pyplot.imshow(), I can see that the connection between the raspberry pi camera and opencv is working through the bcm2835-v4l2 connection.
However when using opencv.imshow() the window result in a blackbox, nothing is displayed.
Update: so while testing I found out that when I perform the following task
import cv2
import matplotlib
camera = cv2.VideoCapture(0)
grab,frame = camera.read()
matplotlib.pyplot.imshow(frame)
grab,frame = camera.read()
matplotlib.pyplot.imshow(frame)
update was solved and not related to the main problem. This was a buffering issue. Appears to have no correlation to cv2.imshow()
on a raspberry you should work with
from picamera import PiCamera
checkout pyimagesearch for that
I followed a tut Click me! and i get un-expected results: my code
from PIL import ImageGrab, ImageOps
import pyautogui
import time
from numpy import *
class Cordinates():
replayBtn = (960,355)
dinosaur = (784,375)
#770x360, 770x365
def restartGame():
pyautogui.click(Cordinates.replayBtn)
def pressSpace():
pyautogui.keyDown('space')
time.sleep(0.05)
print("Jump")
pyautogui.keyUp('space')
def imageGrab():
box = (Cordinates.dinosaur[0]+435, Cordinates.dinosaur[1]+25,
Cordinates.dinosaur[1]+335, 10)
image = ImageGrab.grab(box)
grayImage = ImageOps.grayscale(image)
a = array(grayImage.getcolors())
return a.sum()
def main():
restartGame()
while True:
if imageGrab()!=1447:
#pressSpace()
print(imageGrab)
time.sleep(0.1)
time.sleep(2)
main()
and the print i added for debug gives me
<function imageGrab at 0x079CBD68>
What can i fix to make this work?
here
if imageGrab()!=1447:
#pressSpace()
print(imageGrab)
time.sleep(0.1)
you print(imageGrab) like variable but you need to print like method
print(imageGrab())
you printed out a function, not a result of a function