Skip to content

Commit

Permalink
First mini project
Browse files Browse the repository at this point in the history
  • Loading branch information
Riyazyx committed May 23, 2023
1 parent 3690d27 commit 774dc61
Show file tree
Hide file tree
Showing 14 changed files with 33,697 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
__pycache__
venv
9 changes: 9 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
language: python
python:
- "3.7"
# command to install dependencies
cache: pip
install:
- pip install -r requirements.txt
# command to run tests
script: python main.py
2 changes: 2 additions & 0 deletions Attendance/Attendance_2019-08-24_14-44-53.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Id,Name,Date,Time
15,['jawad'],2019-08-24,14:44:39
3 changes: 3 additions & 0 deletions Attendance/Attendance_2023-05-20_19-59-45.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
,Id,Name,Date,Time
0,4567,syed,2023-05-20,19:58:38
1,5076,Riyaz,2023-05-20,19:58:57
3 changes: 3 additions & 0 deletions Attendance/Attendance_2023-05-23_18-32-27.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
,Id,Name,Date,Time
0,163,reehu,2023-05-23,18:31:50
1,1234,riyaz,2023-05-23,18:32:21
83 changes: 83 additions & 0 deletions Capture_Image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import csv

import cv2
import os

import os.path
# counting the numbers


def is_number(s):
try:
float(s)
return True
except ValueError:
pass

try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass

return False



# Take image function

def takeImages():


Id = input("Enter Your Id: ")
name = input("Enter Your Name: ")

if(is_number(Id) and name.isalpha()):
cam = cv2.VideoCapture(0)
harcascadePath = "haarcascade_frontalface_default.xml"
detector = cv2.CascadeClassifier(harcascadePath)
sampleNum = 0

while(True):
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, 1.3, 5, minSize=(30,30),flags = cv2.CASCADE_SCALE_IMAGE)
for(x,y,w,h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (10, 159, 255), 2)
#incrementing sample number
sampleNum = sampleNum+1
#saving the captured face in the dataset folder TrainingImage
cv2.imwrite("TrainingImage" + os.sep +name + "."+Id + '.' +
str(sampleNum) + ".jpg", gray[y:y+h, x:x+w])
#display the frame
cv2.imshow('frame', img)
#wait for 100 miliseconds
if cv2.waitKey(100) & 0xFF == ord('q'):
break
# break if the sample number is more than 100
elif sampleNum > 100:
break
cam.release()
cv2.destroyAllWindows()
res = "Images Saved for ID : " + Id + " Name : " + name
header=["Id", "Name"]
row = [Id, name]
if(os.path.isfile("StudentDetails"+os.sep+"StudentDetails.csv")):
with open("StudentDetails"+os.sep+"StudentDetails.csv", 'a+') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(j for j in row)
csvFile.close()
else:
with open("StudentDetails"+os.sep+"StudentDetails.csv", 'a+') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(i for i in header)
writer.writerow(j for j in row)
csvFile.close()
else:
if(is_number(Id)):
print("Enter Alphabetical Name")
if(name.isalpha()):
print("Enter Numeric ID")


85 changes: 85 additions & 0 deletions Recognize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import datetime
import os
import time

import cv2
import pandas as pd


#-------------------------
def recognize_attendence():
recognizer = cv2.face.LBPHFaceRecognizer_create() # cv2.createLBPHFaceRecognizer()
recognizer.read("./TrainingImage/Trainner.yml")
harcascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(harcascadePath)
df = pd.read_csv("StudentDetails"+os.sep+"StudentDetails.csv")
font = cv2.FONT_HERSHEY_SIMPLEX
col_names = ['Id', 'Name', 'Date', 'Time']
attendance = pd.DataFrame(columns=col_names)

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video width
cam.set(4, 480) # set video height
# Define min window size to be recognized as a face
minW = 0.1 * cam.get(3)
minH = 0.1 * cam.get(4)

while True:
_,im = cam.read()
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, 1.2, 5,minSize = (int(minW), int(minH)),flags = cv2.CASCADE_SCALE_IMAGE)
for(x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x+w, y+h), (10, 159, 255), 2)
Id, conf = recognizer.predict(gray[y:y+h, x:x+w])

if conf < 100:

aa = df.loc[df['Id'] == Id]['Name'].values
confstr = " {0}%".format(round(100 - conf))
tt = str(Id)+"-"+aa


else:
Id = ' Unknown '
tt = str(Id)
confstr = " {0}%".format(round(100 - conf))

if (100-conf) > 67:
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
aa = str(aa)[2:-2]
attendance.loc[len(attendance)] = [Id, aa, date, timeStamp]

tt = str(tt)[2:-2]
if(100-conf) > 67:
tt = tt + " [Pass]"
cv2.putText(im, str(tt), (x+5,y-5), font, 1, (255, 255, 255), 2)
else:
cv2.putText(im, str(tt), (x + 5, y - 5), font, 1, (255, 255, 255), 2)

if (100-conf) > 67:
cv2.putText(im, str(confstr), (x + 5, y + h - 5), font,1, (0, 255, 0),1 )
elif (100-conf) > 50:
cv2.putText(im, str(confstr), (x + 5, y + h - 5), font, 1, (0, 255, 255), 1)
else:
cv2.putText(im, str(confstr), (x + 5, y + h - 5), font, 1, (0, 0, 255), 1)



attendance = attendance.drop_duplicates(subset=['Id'], keep='first')
cv2.imshow('Attendance', im)
if (cv2.waitKey(1) == ord('q')):
break
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
Hour, Minute, Second = timeStamp.split(":")
fileName = "Attendance"+os.sep+"Attendance_"+date+"_"+Hour+"-"+Minute+"-"+Second+".csv"
attendance.to_csv(fileName, index=True)
print("Attendance Successful")
cam.release()
cv2.destroyAllWindows()


1 change: 1 addition & 0 deletions StudentDetails/StudentDetails.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Id,Name
55 changes: 55 additions & 0 deletions Train_Image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import os
import time
import cv2
import numpy as np
from PIL import Image
from threading import Thread



# -------------- image labesl ------------------------

def getImagesAndLabels(path):
# get the path of all the files in the folder
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
# print(imagePaths)

# create empth face list
faces = []
# create empty ID list
Ids = []
# now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
# loading the image and converting it to gray scale
pilImage = Image.open(imagePath).convert('L')
# Now we are converting the PIL image into numpy array
imageNp = np.array(pilImage, 'uint8')
# getting the Id from the image
Id = int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces.append(imageNp)
Ids.append(Id)
return faces, Ids


# ----------- train images function ---------------
def TrainImages():
recognizer = cv2.face.LBPHFaceRecognizer_create() # recognizer = cv2.face.LBPHFaceRecognizer_create()
harcascadePath = "haarcascade_frontalface_default.xml"
detector = cv2.CascadeClassifier(harcascadePath)
faces, Id = getImagesAndLabels("TrainingImage")
Thread(target = recognizer.train(faces, np.array(Id))).start()
# Below line is optional for a visual counter effect
Thread(target = counter_img("TrainingImage")).start()
recognizer.save("TrainingImage"+os.sep+"Trainner.yml")
print("All Images")

# Optional, adds a counter for images trained (You can remove it)
def counter_img(path):
imgcounter = 1
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
for imagePath in imagePaths:
print(str(imgcounter) + " Images Trained", end="\r")
time.sleep(0.008)
imgcounter += 1

23 changes: 23 additions & 0 deletions automail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import yagmail
import os
import datetime
date = datetime.date.today().strftime("%B %d, %Y")
path = 'Attendance'
os.chdir(path)
files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime)
newest = files[-1]
filename = newest
sub = "Attendance Report for " + str(date)
receiver = "[email protected]"
body = "Attendance report"
# mail information
yag = yagmail.SMTP("[email protected]", "jeynagodjcamknoq")

# sent the mail
yag.send(
to=receiver,
subject=sub, # email subject
contents=body, # email body
attachments= filename # file attached
)
print("Email Sent!")
35 changes: 35 additions & 0 deletions check_camera.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

def camer():
import cv2

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# To capture video from webcam.
cap = cv2.VideoCapture(0)

while True:
# Read the frame
_, img = cap.read()

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detect the faces
faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(30, 30),flags = cv2.CASCADE_SCALE_IMAGE)

# Draw the rectangle around each face
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (10,159,255), 2)


# Display
cv2.imshow('Webcam Check', img)

# Stop if escape key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Release the VideoCapture object
cap.release()
cv2.destroyAllWindows()
Loading

0 comments on commit 774dc61

Please sign in to comment.