multi-threaded face detection opencv - python

I have a script for single-threaded sequential face detection in a photo, and a script for cutting out faces. How do I convert to multithreading? So that the images are not processed sequentially, but simultaneously, parallel to each other.
import os
import cv2
import numpy as np
# Define paths
base_dir = os.path.dirname(__file__)
prototxt_path = os.path.join(base_dir + 'data/deploy.prototxt')
caffemodel_path = os.path.join(base_dir + 'data/weights.caffemodel')
# Read the model
model = cv2.dnn.readNetFromCaffe(prototxt_path, caffemodel_path)
# Create directory 'updated_images' if it does not exist
if not os.path.exists('updated_images'):
print("New directory created")
os.makedirs('updated_images')
# Loop through all images and save images with marked faces
for file in os.listdir(base_dir + 'images'):
file_name, file_extension = os.path.splitext(file)
if (file_extension in ['.png','.jpg']):
print("Image path: {}".format(base_dir + 'images/' + file))
image = cv2.imread(base_dir + 'images/' + file)
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
model.setInput(blob)
detections = model.forward()
# Create frame around face
for i in range(0, detections.shape[2]):
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
confidence = detections[0, 0, i, 2]
# If confidence > 0.5, show box around face
if (confidence > 0.5):
cv2.rectangle(image, (startX, startY), (endX, endY), (255, 255, 255), 2)
cv2.imwrite(base_dir + 'updated_images/' + file, image)
print("Image " + file + " converted successfully")
I tried to push the face detection and selection into def and then monitor the parallel streams through pool and map, but I am very weak in this, and obviously did something wrong. The script just stopped working.

Here is how I would do it:
import os
import cv2
import numpy as np
import threading
base_dir = os.path.dirname(__file__)
prototxt_path = os.path.join(base_dir + 'data/deploy.prototxt')
caffemodel_path = os.path.join(base_dir + 'data/weights.caffemodel')
model = cv2.dnn.readNetFromCaffe(prototxt_path, caffemodel_path)
if not os.path.exists('updated_images'):
print("New directory created")
os.makedirs('updated_images')
def process(file, base_dir):
print("Image path: {}".format(base_dir + 'images/' + file))
image = cv2.imread(base_dir + 'images/' + file)
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
model.setInput(blob)
detections = model.forward()
h, w = image.shape[:2]
for i in range(detections.shape[2]):
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
startX, startY, endX, endY = box.astype("int")
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
cv2.rectangle(image, (startX, startY), (endX, endY), (255, 255, 255), 2)
cv2.imwrite(base_dir + 'updated_images/' + file, image)
print("Image " + file + " converted successfully")
for file in os.listdir(base_dir + 'images'):
file_name, file_extension = os.path.splitext(file)
if file_extension in ['.png','.jpg']:
thread = threading.Thread(target=process, args=(file, base_dir))
thread.start()
Most of it is the same as your code, except a large chunk is now in a function. I also took the liberty of removing some redundant code, such as how you don't need parenthesis to unpack an iterable, nor do you need parenthesis to do if statements.
As I don't have the files you open in your code, I'm unable to test it out, hence if there are any problems, there might be something I missed, so feel free to ping me if that happens.

Related

how to recognize through both webcame and ipcamera using opencv

iam beginner in image processing i have trained my data using cafee model and recognize through webcame , but i have to connect both my webcamera as well as ipcamera(phone camera) ,Following is the code im using for recognition
import numpy as np
import pickle
import os
import cv2
import time
import imutils
curr_path = os.getcwd()
# print("Loading face detection model")
proto_path = os.path.join(curr_path, 'model', 'deploy.prototxt')
model_path = os.path.join(curr_path, 'model', 'res10_300x300_ssd_iter_140000.caffemodel')
face_detector = cv2.dnn.readNetFromCaffe(prototxt=proto_path, caffeModel=model_path)
# print("Loading face recognition model")
recognition_model = os.path.join(curr_path, 'model', 'openface_nn4.small2.v1.t7')
face_recognizer = cv2.dnn.readNetFromTorch(model=recognition_model)
recognizer = pickle.loads(open('recognizer.pickle', "rb").read())
le = pickle.loads(open('le.pickle', "rb").read())
print("Start capturing video....")
# address="http://192.168.210.242:8080/video"
# vid = cv2.VideoCapture(address)
vid = cv2.VideoCapture(0)
time.sleep(1)
while True:
ret, frame = vid.read()
frame = imutils.resize(frame, width=600)
(h, w) = frame.shape[:2]
image_blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0), False, False)
face_detector.setInput(image_blob)
face_detections = face_detector.forward()
for i in range(0, face_detections.shape[2]):
confidence = face_detections[0, 0, i, 2]
if confidence >= 0.5:
box = face_detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype('int')
face = frame[startY:endY, startX:endX]
(fH, fW) = face.shape[:2]
face_blob = cv2.dnn.blobFromImage(face, 1.0/255, (96, 96), (0, 0, 0), True, False)
face_recognizer.setInput(face_blob)
vec = face_recognizer.forward()
preds = recognizer.predict_proba(vec)[0]
j = np.argmax(preds)
proba = preds[j]
name = le.classes_[j]
text = "{}: {:.2f}".format(name, proba * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
the coding is working good, One more thing if i run this individually(on webcame and ip camera) then it also works fine.but if i try to run both at the same time then the code is not working ,
please have a check on this issue thankyou.

When running code I get an opencv cv2 error

This is the code im trying to run that I found on this video https://www.youtube.com/watch?v=Ax6P93r32KU
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils.video import VideoStream
import numpy as np
import imutils
import time
import cv2
import os
def detect_and_predict_mask(frame, faceNet, maskNet):
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),
(104.0, 177.0, 123.0))
faceNet.setInput(blob)
detections = faceNet.forward()
print(detections.shape)
faces = []
locs = []
preds = []
# loop over the detections
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
(startX, startY) = (max(0, startX), max(0, startY))
(endX, endY) = (min(w - 1, endX), min(h - 1, endY))
face = frame[startY:endY, startX:endX]
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
face = cv2.resize(face, (224, 224))
face = img_to_array(face)
face = preprocess_input(face)
faces.append(face)
locs.append((startX, startY, endX, endY))
if len(faces) > 0:
faces = np.array(faces, dtype="float32")
preds = maskNet.predict(faces, batch_size=32)
return (locs, preds)
prototxtPath = r"face_detector\deploy.prototxt"
weightsPath = r"face_detector\res10_300x300_ssd_iter_140000.caffemodel"
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)
maskNet = load_model("mask_detector.model")
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
while True:
frame = vs.read()
frame = imutils.resize(frame, width=400)
(locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)
for (box, pred) in zip(locs, preds):
# unpack the bounding box and predictions
(startX, startY, endX, endY) = box
(mask, withoutMask) = pred
label = "Mask" if mask > withoutMask else "No Mask"
color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
cv2.putText(frame, label, (startX, startY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cv2.destroyAllWindows()
vs.stop()
This is what happens when I run the code
PS C:\Users\rainb> & C:/Users/rainb/AppData/Local/Programs/Python/Python38/python.exe
c:/Users/Public/Desktop/Python_Work/Face-Mask-Detection-master/detect_mask_video.py
2021-03-15 22:36:04.855886: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not
load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2021-03-15 22:36:04.866930: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart
dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
File "c:/Users/Public/Desktop/Python_Work/Face-Mask-Detection-master/detect_mask_video.py", line 77, in <module>
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1121: error: (-2:Unspecified error) FAILED: fs.is_open(). Can't open "face_detector\deploy.prototxt" in function 'cv::dnn::ReadProtoFromTextFile'
The file location C:\projects\opencv-python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1121: does not exist, and I was wondering how to change that file location to something else, or find a different way to fix the problem.
I think you have error in the file extension. May be file called deploy.proto.txt ?
And one moment yet, check the real path, where this file is storaged
i also refer this same code...i also felt the same error..
datapath is not correct thats y...
if you run this in colab you might change the datapath
like this
prototxtPath ='/content/drive/MyDrive/MINIPROJECT/Face-Mask-Detection-master/face_detector/deploy.prototxt'- this is my datapath u correct just it with ur path

How can use I use multithreading to speed this up?

The code below goes through files on my HDD which has 620,000 frames which I am extracting the faces from using OpenCV's DNN face detector. It works fine but it takes about 1 second per frame = 172 hours.
So I want to use multithreading to speed this up but am not sure how to do so.
NOTE: I have 4 CPU cores on my laptop and my HDD has read and write speeds of about 100 MB/s
Example of the file path : /Volumes/HDD/frames/Fold1_part1/01/0/04541.jpg
frames_path = "/Volumes/HDD/frames"
path_HDD = "/Volumes/HDD/Data"
def filePath(path):
for root, directories, files in os.walk(path, topdown=False):
for file in files:
if (directories == []):
pass
elif (len(directories) > 3):
pass
elif (len(root) == 29):
pass
else:
# Only want the roots with /Volumes/HDD/Data/Fold1_part1/01
for dir in directories:
path_video = os.path.join(root, dir)
for r, d, f in os.walk(path_video, topdown=False):
for fe in f:
fullPath = r[:32]
label = r[-1:]
folds = path_video.replace("/Volumes/HDD/Data/", "")
finalPath = os.path.join(frames_path, folds)
finalImage = os.path.join(finalPath, fe)
fullImagePath = os.path.join(path_video, fe)
try :
if (os.path.exists(finalPath) == False):
os.makedirs(finalPath)
extractFaces(fullImagePath, finalImage)
except OSError as error:
print(error)
sys.exit(0)
def extractFaces(imageTest, savePath):
model = "/Users/yudhiesh/Downloads/deep-learning-face-detection/res10_300x300_ssd_iter_140000.caffemodel"
prototxt = "/Users/yudhiesh/Downloads/deep-learning-face-detection/deploy.prototxt.txt"
net = cv2.dnn.readNet(model, prototxt)
# load the input image and construct an input blob for the image
# by resizing to a fixed 300x300 pixels and then normalizing it
image = cv2.imread(imageTest)
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,(300, 300), (104.0, 177.0, 123.0))
print(f'Current file path {imageTest}')
# pass the blobs through the network and obtain the predictions
print("Computing object detections....")
net.setInput(blob)
detections = net.forward()
# Detect face with highest confidence
for i in range(0, detections.shape[2]):
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
confidence = detections[0, 0, i, 2]
# If confidence > 0.5, save it as a separate file
if (confidence > 0.5):
frame = image[startY:endY, startX:endX]
rect = dlib.rectangle(startX, startY, endX, endY)
image = image[startY:endY, startX:endX]
print(f'Saving image to {savePath}')
cv2.imwrite(savePath, image)
if __name__ == "__main__":
filePath(path_HDD)
Managed to cut the time down to 0.09-0.1 seconds per image. Thanks for the suggestion to use ProcessPoolExecutor.
frames_path = "/Volumes/HDD/frames"
path_HDD = "/Volumes/HDD/Data"
def filePath(path):
for root, directories, files in os.walk(path, topdown=False):
for file in files:
if (directories == []):
pass
elif (len(directories) > 3):
pass
elif (len(root) == 29):
pass
else:
# Only want the roots with /Volumes/HDD/Data/Fold1_part1/01
for dir in directories:
path_video = os.path.join(root, dir)
for r, d, f in os.walk(path_video, topdown=False):
for fe in f:
fullPath = r[:32]
label = r[-1:]
folds = path_video.replace("/Volumes/HDD/Data/", "")
finalPath = os.path.join(frames_path, folds)
finalImage = os.path.join(finalPath, fe)
fullImagePath = os.path.join(path_video, fe)
try :
if (os.path.exists(finalPath) == False):
os.makedirs(finalPath)
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(extractFaces(fullImagePath, finalImage))
except OSError as error:
print(error)
sys.exit(0)
def extractFaces(imageTest, savePath):
model = "/Users/yudhiesh/Downloads/deep-learning-face-detection/res10_300x300_ssd_iter_140000.caffemodel"
prototxt = "/Users/yudhiesh/Downloads/deep-learning-face-detection/deploy.prototxt.txt"
net = cv2.dnn.readNet(model, prototxt)
# load the input image and construct an input blob for the image
# by resizing to a fixed 300x300 pixels and then normalizing it
image = cv2.imread(imageTest)
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,(300, 300), (104.0, 177.0, 123.0))
print(f'Current file path {imageTest}')
# pass the blobs through the network and obtain the predictions
print("Computing object detections....")
net.setInput(blob)
detections = net.forward()
# Detect face with highest confidence
for i in range(0, detections.shape[2]):
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
confidence = detections[0, 0, i, 2]
# If confidence > 0.5, save it as a separate file
if (confidence > 0.5):
frame = image[startY:endY, startX:endX]
rect = dlib.rectangle(startX, startY, endX, endY)
image = image[startY:endY, startX:endX]
print(f'Saving image to {savePath}')
cv2.imwrite(savePath, image)
if __name__ == "__main__":
filePath(path_HDD)

writing pgm images with cv2.imwrite()

I want to write my detected images with caffe pre-trained model in openCV and it works with jpg or other similar formats but it's showing an error
SystemError: <built-in function imwrite> returned NULL without setting an error
and here is my code
import os
import cv2
import numpy
from imutils import paths
# DIR_PATH = os.path.dirname(os.path.realpath('dataset/'))
DIR_PATH = (list(paths.list_images('dataset')))
print(DIR_PATH)
if not os.path.exists('Output'):
os.makedirs('Output')
MODEL = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
# print(DIR_PATH)
for file in DIR_PATH:
filename, file_extension = os.path.splitext(file)
if (file_extension in ['.png', '.jpg', '.pgm', '.jpeg']):
image = cv2.imread(file)
(h, w) = image.shape[:2]
print("Proccess one started ")
blob = cv2.dnn.blobFromImage(cv2.resize(
image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123, 0))
MODEL.setInput(blob)
detections = MODEL.forward()
print("Proccess Two started ")
COUNT = 0
for i in range(0, detections.shape[2]):
box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
confidence = detections[0, 0, i, 2]
if confidence > 0.165:
cv2.rectangle(image, (startX, startY),
(endX, endY), (0, 255, 0), 2)
COUNT = COUNT + 1
export_name = filename.split("\\")
print(export_name)
if file_extension == '.pgm' :
cv2.imwrite('Output/'+export_name[1]+export_name[2], image, 0)
else:
cv2.imwrite('Output/'+export_name[1]+file_extension, image)
print("Face detection complete for image " +
file + " (" + str(COUNT) + ") faces found!")
and also I've checked my values.
images with PGM format has been loading but and detecting faces but the number of faces is too much and it's not writing at all with cv2.imwrite
here is the exact problem
if file_extension == '.pgm' :
cv2.imwrite('Output/'+export_name[1]+export_name[2], image, 0)
else:
cv2.imwrite('Output/'+export_name[1]+file_extension, image)
OpenCV does not read paths in OS paths or PathLib formats, it reads a string so change your code to:
if file_extension == '.pgm':
fname = 'Output/{}{}'.format(export_name[1],export_name[2])
cv2.imwrite(fname, image, 0)
else:
fname = 'Output/{}{}'.format(export_name[1],file_extension)
cv2.imwrite(fname, image)

Read multi images in a folder python

I am trying to read read multi images on a folder and do some processing. I have a code that extracts facial landmark coordinates. But I can apply this code to only one image. I want the script to work with all images in the folder. I have read some solutions but they didn't work for me. Can you tell me how can I apply a loop for this?
This is my code:
import numpy as np
import cv2
import dlib
import os
from glob import glob
mouth_matrice= open("C:/Users/faruk/Desktop/matrices/mouth.txt","w")
lefteye_matrice= open("C:/Users/faruk/Desktop/matrices/lefteye.txt","w")
righteye_matrice= open("C:/Users/faruk/Desktop/matrices/righteye.txt","w")
cascPath = ("C:/opencv/sources/data/haarcascades_cuda/haarcascade_frontalface_default.xml")
all_matrice= open("C:/Users/faruk/Desktop/matrices/all.txt","w")
#imagePath = ("C:/Users/faruk/Desktop/Dataset/Testing/342_spontaneous_smile_4 (2-17-2018 8-37-58 PM)/342_spontaneous_smile_4 357.jpg")
mypath=os.path.join("c:", os.sep, "Users", "faruk", "Desktop", "Dataset","Testing2")
PREDICTOR_PATH = ("C:/Users/faruk/Desktop/Working projects/facial-landmarks/shape_predictor_68_face_landmarks.dat")
JAWLINE_POINTS = list(range(0, 17))
RIGHT_EYEBROW_POINTS = list(range(17, 22))
LEFT_EYEBROW_POINTS = list(range(22, 27))
NOSE_POINTS = list(range(27, 36))
#RIGHT_EYE_POINTS = list(range(36, 42))
RIGHT_EYE_POINTS = list([36,39])
ALL_POINTS= list([36,39,42,45,48,51,54,57])
##LEFT_EYE_POINTS = list(range(42, 48))
LEFT_EYE_POINTS = list([42, 45])
##MOUTH_OUTLINE_POINTS = list(range(48, 61))
MOUTH_OUTLINE_POINTS = list([48,51,54,57])
MOUTH_INNER_POINTS = list(range(61, 68))
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
predictor = dlib.shape_predictor(PREDICTOR_PATH)
# Read the image
cv2.namedWindow('Landmarks found',cv2.WINDOW_NORMAL)
cv2.resizeWindow('Landmarks found', 800,800)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.05,
minNeighbors=5,
minSize=(100, 100),
flags=cv2.CASCADE_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Converting the OpenCV rectangle coordinates to Dlib rectangle
dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))
landmarks = np.matrix([[p.x, p.y]
for p in predictor(image, dlib_rect).parts()])
#landmarks_display = landmarks[LEFT_EYE_POINTS]
landmarks_display = np.matrix(landmarks[ALL_POINTS])
for idx, point in enumerate(landmarks_display):
pos = (point[0, 0], point[0, 1])
cv2.circle(image, pos, 2, color=(0, 255, 255), thickness=-1)
np.savetxt(all_matrice,landmarks_display,fmt='%.f',newline=',')
all_matrice.close()
# Draw a rectangle around the faces
cv2.imshow("Landmarks found", image)
cv2.waitKey(0)
You can use something like this to get paths of all images in a directory:
import os
# Folder with images
directory = 'c:/users/username/path/'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
image_path = os.path.join(directory, filename)
# Your code
continue
else:
continue
You need to add your code and process each path.
Hope this helps.
Edit:
I have no way to test it and it certainly needs a cleanup but might just work. Not sure what image extensions you want to include so i only included jpg.
import os
import numpy as np
import cv2
import dlib
# Chage directory path to the path of your image folder
directory = 'c:/users/admin/desktop/'
mouth_matrice= open("C:/Users/faruk/Desktop/matrices/mouth.txt","w")
lefteye_matrice= open("C:/Users/faruk/Desktop/matrices/lefteye.txt","w")
righteye_matrice= open("C:/Users/faruk/Desktop/matrices/righteye.txt","w")
cascPath = ("C:/opencv/sources/data/haarcascades_cuda/haarcascade_frontalface_default.xml")
all_matrice= open("C:/Users/faruk/Desktop/matrices/all.txt","w")
mypath=os.path.join("c:", os.sep, "Users", "faruk", "Desktop", "Dataset","Testing2")
PREDICTOR_PATH = ("C:/Users/faruk/Desktop/Working projects/facial-landmarks/shape_predictor_68_face_landmarks.dat")
JAWLINE_POINTS = list(range(0, 17))
RIGHT_EYEBROW_POINTS = list(range(17, 22))
LEFT_EYEBROW_POINTS = list(range(22, 27))
NOSE_POINTS = list(range(27, 36))
#RIGHT_EYE_POINTS = list(range(36, 42))
RIGHT_EYE_POINTS = list([36,39])
ALL_POINTS= list([36,39,42,45,48,51,54,57])
##LEFT_EYE_POINTS = list(range(42, 48))
LEFT_EYE_POINTS = list([42, 45])
##MOUTH_OUTLINE_POINTS = list(range(48, 61))
MOUTH_OUTLINE_POINTS = list([48,51,54,57])
MOUTH_INNER_POINTS = list(range(61, 68))
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
predictor = dlib.shape_predictor(PREDICTOR_PATH)
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
imagePath=os.path.join(directory, filename)
cv2.namedWindow('Landmarks found',cv2.WINDOW_NORMAL)
cv2.resizeWindow('Landmarks found', 800,800)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.05,
minNeighbors=5,
minSize=(100, 100),
flags=cv2.CASCADE_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Converting the OpenCV rectangle coordinates to Dlib rectangle
dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))
landmarks = np.matrix([[p.x, p.y] for p in predictor(image, dlib_rect).parts()])
#landmarks_display = landmarks[LEFT_EYE_POINTS]
landmarks_display = np.matrix(landmarks[ALL_POINTS])
for idx, point in enumerate(landmarks_display):
pos = (point[0, 0], point[0, 1])
cv2.circle(image, pos, 2, color=(0, 255, 255), thickness=-1)
np.savetxt(all_matrice,landmarks_display,fmt='%.f',newline=',')
all_matrice.close()
# Draw a rectangle around the faces
cv2.imshow("Landmarks found", image)
cv2.waitKey(0)
continue
else:
continue
P.s You should try and learn basic programming concepts before you try to tackle something like face recognition or image processing.

Categories

Resources