Issue With Opencv Face Detection - python

I have been trying to get the openCV 2.4.13 python27 face Detection from images please help.The error that I get is:
Traceback (most recent call last):
File "C:\Users\sam_o\Desktop\Alrehman\Attendance.py", line 36, in <module>
profile = getProfile(id)
File "C:\Users\sam_o\Desktop\Alrehman\Attendance.py", line 19, in getProfile
profile = none
NameError: global name 'none' is not defined
The code I wrote is as follows:
import cv2,os
import numpy as np
from PIL import Image
import pickle
import sqlite3
recognizer = cv2.createLBPHFaceRecognizer()
cascadePath = "Classifiers/face.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
path = 'EmployeeRecord'
def getProfile(id):
conn=sqlite3.connect("Alrehman.db")
cmd="SELECT * FROM Person WHERE ID="+str(id)
cursor=conn.execute(cmd)
profile=none
for row in cursor:
profile=row
conn.close()
return profile
cam = cv2.VideoCapture(0)
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) #Creates a font
while True:
ret, im =cam.read()
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
faces=faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE)
for(x,y,w,h) in faces:
id, conf = recognizer.predict(gray[y:y+h,x:x+w])
cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
profile=getProfile(id)
if(profile!=None):
cv2.cv.PutText(cv2.cv.fromarray(im),str(profile[1]), (x,y+h+30),font, 255) #Draw the text
cv2.cv.PutText(cv2.cv.fromarray(im),str(profile[2]), (x,y+h+60),font, 255) #Draw the text
cv2.imshow('im',im)
cv2.waitKey(10)
Does anyone have any idea what I might be doing wrong here?

It looks like either your camera is not capturing a photo, or capturing a grayscale photo. (error code 215 is common in such cases, in other opencv functions as well)
You can test this further by loading a sample image from the computer, and passing that to cv2.cvtColor().

I tried it This is code is working for me.....
import cv2
import numpy as np
import os
import pickle
import sqlite3
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
def getProfile(id):
conn=sqlite3.connect("FaceBase.db")
cmd="SELECT * FROM People WHERE ID="+str(id)
cursor=conn.execute(cmd)
profile=None
for row in cursor:
profile=row
conn.close()
return profile
cam=cv2.VideoCapture(0);
rec=cv2.createLBPHFaceRecognizer();
rec.load("recognizer\\trainner.yml");
id=0
font=cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_COMPLEX_SMALL,1,1,0,1)
while(True):
ret,img=cam.read();
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
id,conf=rec.predict(gray[y:y+h,x:x+w])
profile=getProfile(id)
if(profile!=None):
cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[1]),(x,y+h+30),font,255);
cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[2]),(x,y+h+60),font,255);
cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[3]),(x,y+h+90),font,255);
# cv2.cv.PutText(cv2.cv.fromarray(img),str(profile[4]),(x,y+h+30),font,255);
cv2.imshow("Face",img);
if(cv2.waitKey(1)==ord('q')):
break;
cam.release();
cv2.destoryAllWindows()

Related

an notAdirectoryerror in python3.7

i am making a face recognition program but i am facing NotADirectoryError error whenever i run it
i tried coping the full directory as well as using os.join.path and nothing worked
i am using pycharm.
import face_recognition
import cv2
import os
import numpy
os.chdir('C:/Users/a/Desktop/ftp')
KNOWN_FACE_DIR = "known_faces"
print(KNOWN_FACE_DIR)
#UNKNOWN_FACES_DIR = r"unknown_faces"
TOLERANCE = 0.6
FRANE_THICKNESS = 3
FONT_THICKNESS = 2
MODEL = "cnn"
video = cv2.VideoCapture(0)
print("loading known faces ")
known_faces = []
known_names = []
for name in os.listdir(KNOWN_FACE_DIR):
for filename in os.listdir(f"{KNOWN_FACE_DIR}/{name}"):
image = face_recognition.load_image_file(f"{KNOWN_FACE_DIR}/{name}/{filename}")
print("processing unknown faces")
while True :
#print(filename)
#image = face_recognition.load_image_file(f"{UNKNOWN_FACES_DIR}/{filename}")
ret ,image = video.read()
locations = face_recognition.face_locations(image, model=MODEL)
encodings = face_recognition.face_encodings(image, locations)
#image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
for face_encoding, face_location in zip(encodings, locations):
results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE)
match = None
if True in results:
match = known_names[results.index(True)]
print(f"Match found:{match}")
top_left = (face_location[3], face_location[0])
bottom_right = (face_location[1], face_location[2])
color = [0,255,0]
cv2.rectangle(image, top_left, bottom_right, color, FRANE_THICKNESS)
top_left = (face_location[3], face_location[2])
bottom_right = (face_location[1], face_location[2]+22)
cv2.rectangle(image, top_left, bottom_right, color, cv2.FILLED)
cv2.putText(image, match, (face_location[3]+10,face_location[2]+15).cv2.FONT_HERSHEY_SIMPLEX,0.5,(200,200,200),FONT_THICKNESS)
cv2.imshow(filename,image)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyWindow(filename)
the error
Traceback (most recent call last):
File "C:\Users\a\Desktop\ftp\face recognition.py", line 27, in <module>
for filename in os.listdir(f"{KNOWN_FACE_DIR}/{name}"):
NotADirectoryError: [WinError 267] The directory name is invalid: 'known_faces/Majd.jpg'
i tried coping the whole directory
and using os.join.path although i am now sure i used it correctly
The os.listdir function requires a directory name, and something called Madj.jpg is most likely to be a JPEG file rather than a directory.
It looks like your assumption that everything in C:/Users/a/Desktop/ftp/known_faces is a directory containing files that you want to process may not be correct.

VIDEOIO(CV_IMAGES): raised OpenCV exception:

When I run the code, I got this error:
[ERROR:0] global /io/opencv/modules/videoio/src/cap.cpp (116) open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.1.2) /io/opencv/modules/videoio/src/cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'icvExtractPattern'
Please show me how to fix it. Thank you very much.
And this is my source code:
# Program for finding the location of a person based a difference images
# The video file name should be specified.
import os
from typing import Dict, List, Tuple
import datetime
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
#import sklearn
#from sklearn import metrics
#from sklearn import neural_network
#import sklearn_util
import cv2
def guess_location(src):
index = np.array([i for i in enumerate(src)])
index_sum_sort10 = index[index[:, -1].argsort()][::-1][0:40].T
location = int(np.average(index_sum_sort10[0]))
return location
def calculate_location(src):
row_max_location = guess_location(np.sum(src, axis=0))
col_max_location = guess_location(np.sum(src, axis=1))
return (row_max_location, col_max_location)
#
# Read video frames from a usb-camera / video file,
# and find the location of the person
#
cap = cv2.VideoCapture(0)
v_filename= '/dev/compact-module/Videodata/2021/03/22/1720_00_006686/entity_video_1616401200006.mp4'
#'/media/qf-zhao/68A01144A0111A60/GrayDiffVideo/Image2019_11_18_08_40_00.avi'
cap = cv2.VideoCapture(v_filename)
th_change = 150
th_value = 30
location_back=(0,0)
while(cap.isOpened()):
ret, frame = cap.read()
diff=cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
diff[diff<th_value]=0
if np.max(frame) < th_change:
location=location_back
else:
location = calculate_location(diff)
print("location:", location)
cv2.circle(frame, location, 10, (0,0,255), -1)
cv2.imshow('Result image', frame)
location_back=location
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()

Getting No module named 'picamera' while running FaceRecognition code in Python on RaspberryPi

I am running my Python FaceRecognition code on RaspberryPi but I am getting No module named 'picamera' error. I have tried few solutions but none worked for me. Can someone please figure out what is the problem?
Below is my Python Code:
import cv2
import numpy as np
from imutils.video.pivideostream import PiVideoStream
from imutils.video import FPS
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import argparse
import imutils
#Load pretrained cascade face detection
face_cascade = cv2.CascadeClassifier('lbpcascade_frontalface.xml')
#Load improved FPS video instead of the default Picamera
reader = PiVideoStream().start()
time.sleep(0.2)
#Load the recognizer
rec = cv2.face.createLBPHFaceRecognizer()
#Load trained local binary pattern face data
rec.load("recognizer/trainingData.yml")
id=0
font = cv2.FONT_HERSHEY_SIMPLEX
#Face recognition function
def detectFace(faces,hog,img):
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
result = cv2.face.MinDistancePredictCollector()
rec.predict(hog[y:y+h,x:x+w],result, 0)
id = result.getLabel()
conf = result.getDist()
if(conf<150):
if(id==1):
id="Ibrahim_"+str(conf)
elif(id==2):
id="Minh_"+str(conf)
else:
id="Hyeon_"+str(conf)
else:
id="Unknow"
cv2.putText(img,str(id),(x,y+h),font,1,(255,255,255),2,cv2.LINE_AA)
while(True):
#read each frame in the real-time video
frame = reader.read()
img=frame
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Use histogram equalizer for adjusting face in different light condition
equ = cv2.equalizeHist(gray)
faces = face_cascade.detectMultiScale(equ, 1.05, 5,minSize=(10,10))
#If the face is not frontal face then rotate the face by +30/-30 degree
if len(faces)==0:
rows,cols = equ.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),30,1)
dst = cv2.warpAffine(equ,M,(cols,rows))
faces = face_cascade.detectMultiScale(dst, 1.05, 5,minSize=(10,10))
if len(faces)==0:
rows,cols = equ.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),-30,1)
dst = cv2.warpAffine(equ,M,(cols,rows))
faces = face_cascade.detectMultiScale(dst, 1.05, 5,minSize=(10,10))
detectFace(faces,dst,img)
else:
detectFace(faces,dst,img)
else:
detectFace(faces,equ,img)
cv2.imshow('Face', img)
if(cv2.waitKey(1)==ord('q')):
break;
cap.release()
cv2.destroyAllWindows()
Below is what I run on RaspberryPi terminal and what I get:
(cv) pi#raspberrypi:~/Downloads/Raspberry_pi_face_recognition-master $ python FaceRecognizer.py
Traceback (most recent call last):
File "FaceRecognizer.py", line 3, in <module>
from imutils.video.pivideostream import PiVideoStream
File "/home/pi/.virtualenvs/cv/lib/python3.5/site-packages/imutils/video/pivideostream.py", line 2, in <module>
from picamera.array import PiRGBArray
ImportError: No module named 'picamera'
Just Try it for python3
sudo apt install python3-picamera
sudo -H pip3 install --upgrade picamera[array]
In code file write this steps:
from picamera import PiCamera
camera = PiCamera()
and must be ensure that camera = PiCamera() line is not be in loop.

Background Object detection in face recognition Using OpenCV

I have created a face recognition code using OpenCV. Now the problems occuring are :
-> Sometimes it detects small objects from the wall and show them as me. How can i stop it from doing so ? so that it only detect faces not objets.
-> Whenever a unknown person shows up on scree, it randomly shows any name to it from the database. I waant it to show as a Unknown Face whenever someone unknown hits the cam.
Note : i did not added it to sql database yet but will do it after i get through this.THanks for the help in advance
Data Set creator code:
import cv2
import sqlite3
import numpy as np
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
cam=cv2.VideoCapture(0);
id = raw_input('Enter Your ID : ')
Name = raw_input('Enter Your Name : ')
sampleNum=0;
while(True):
ret,img=cam.read();
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
sampleNum=sampleNum+1;
cv2.imwrite("dataSet/User."+str(id)+"."+str(sampleNum)+".jpg",gray[y:y+h,x:x+w])
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.waitKey(500);
cv2.imshow("Face",img);
cv2.waitKey(1);
if(sampleNum>20):
break;
cam.release()
cv2.destroyAllWindows()
Trainer Code :
import os
import cv2
import numpy as np
from PIL import Image
recognizer=cv2.createLBPHFaceRecognizer();
path='dataSet'
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
faceImg=Image.open(imagePath).convert('L');
faceNp=np.array(faceImg,'uint8')
ID=int(os.path.split(imagePath)[-1].split('.')[1])
faces.append(faceNp)
print ID
IDs.append(ID)
cv2.imshow("training",faceNp)
cv2.waitKey(10)
return IDs, faces
Ids,faces=getImagesWithID(path)
recognizer.train(faces,np.array(Ids))
recognizer.save('recognizer/trainningData.yml')
cv2.destroyAllWindows()
Detector Code :
import cv2
import numpy as np
faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
cam=cv2.VideoCapture(0);
rec=cv2.createLBPHFaceRecognizer();
rec.load("recognizer\\trainningData.yml")
id=0
font=cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_COMPLEX_SMALL,2,2,0,2)
while(True):
ret,img=cam.read()
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
id,conf=rec.predict(gray[y:y+h,x:x+w])
if(id==1):
id="Vivek"
cv2.cv.PutText(cv2.cv.fromarray(img),str(id),(x,y+h),font,255);
cv2.imshow("Face",img);
if(cv2.waitKey(1)==ord('q')):
break;
cam.release()
cv2.destroyAllWindows()

Scan bar code using raspberry pi camera module v2

How to scan barcode using Raspberry pi camera module V2
This is the link to my previously asked question about barcode scanning.
To be more specific:
Hardware :
Raspberry pi
and
Raspberry pi camera module v2 :
https://www.amazon.in/Raspberry-Camera-Board-Module-
V2/dp/B071P2S8LG/ref=sr_1_5?s=computers&ie=UTF8&qid=1525942832&sr=1-5&keywords=raspberry+pi+camera+module
I have tried to scan bar code using
1) pyzbar library
2) SimpleCV
3) OpenCV and zbar
Using Pyzbar :
from PIL import Image
import pyzbar.pyzbar as pyzbar
file_path = 'image.png'
with open(file_path, 'rb') as image_file:
image = Image.open(image_file)
image.load()
codes = pyzbar.decode(Image.open('image.png'))
print('QR codes: %s' % codes)
Using SimpleCV :
from SimpleCV import Color,Camera,Display
cam = Camera() #starts the camera
display = Display()
while(display.isNotDone()):
img = cam.getImage() #gets image from the camera
barcode = img.findBarcode() #finds barcode data from image
if(barcode is not None): #if there is some data processed
barcode = barcode[0]
result = str(barcode.data)
print result #prints result of barcode in python shell
barcode = [] #reset barcode data to empty set
img.save(display) #shows the image on the screen
Using OpenCV :
https://www.pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/
I have tried all three ways to scan barcode but none of them is working.
Using the last code, I am able to detect the barcode location in the image but cannot scan barcode.
Thanks in advance
go through this. it should work.
from pyzbar.pyzbar import decode
from ftplib import FTP
import os
import numpy as np
import cv2
import time
from picamera.array import PiRGBArray
from picamera import PiCamera
fourcc = cv2.VideoWriter_fourcc(*'X264')
def dec(frame):
x=decode(frame)
for i in x:
(x, y, w, h) = i.rect
cv2.rectangle(frame,(x, y),(x + w, y + h),(0, 0, 255),2)
barcodeData = i.data.decode("utf-8")
barcodeType = i.type
return(barcodeData,barcodeType,1)
return('','',0)
camera=PiCamera()
camera.resolution=(1296,730)
camera.framerate=20
rawCapture=PiRGBArray(camera)
time.sleep(0.1)
cv2.namedWindow("Image",cv2.WINDOW_NORMAL)
for frame in camera.capture_continuous(rawCapture,format="bgr",use_video_port=True):
image=frame.array
x,y,p=dec(image)
cv2.imshow("Image",image)
print(x)
print(y)
if cv2.waitKey(2) & 0xFF == ord('q'):
break
rawCapture.truncate(0)
#cap.release()
cv2.destroyAllWindows()

Categories

Resources