def run():
    fd = FD.FaceDetection()
    fr = VR.VggRecogniser()

    fout = createOutFile(VIDEO_PATH, OUT_DIR)
    if not os.path.exists(VIDEO_PATH):
        print 'video not exist...'
        return
    video_capture = cv2.VideoCapture(VIDEO_PATH)
    if not video_capture.isOpened():
        print 'video reading error...'
        return
    fps = int(video_capture.get(cv2.CAP_PROP_FPS))
    print 'fps: ', fps
    num_frame = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
    print 'frame count: ', num_frame

    for count in range(num_frame):
        ret, frame = video_capture.read()
        if not ret or count % fps != 0:
            continue

        _, scores, bboxes = fd.dectectFace(frame)
        imgs = []
        coors = []
        for i in range(len(scores)):
            if scores[i] >= 0.8:
                y1, x1, y2, x2 = bboxes[i]
                y1 = int(y1 * frame.shape[0])
                y2 = int(y2 * frame.shape[0])
                x1 = int(x1 * frame.shape[1])
                x2 = int(x2 * frame.shape[1])
                w = x2 - x1
                h = y2 - y1
                if w > frame.shape[1] * THRES_SIZE and h > frame.shape[
                        0] * THRES_SIZE:
                    face = frame[y1:y2, x1:x2, :]
                    imgs.append(face)
                    coors.append((x1, y1, x2 - x1, y2 - y1))
        if len(imgs) > 0:
            num, res = fr.recognise(imgs)
            ss = count / fps
            mm = ss / 60
            ss = ss % 60
            for k in range(num):
                uid, scr = res[k]
                if scr >= THRES_REG:
                    coor = coors[k]
                    fout.write(
                        '%02d:%02d\t%d %d %d %d\t%s\n' %
                        (mm, ss, coor[0], coor[1], coor[2], coor[3], uid))
                    print('%02d:%02d\t%d %d %d %d\t%s' %
                          (mm, ss, coor[0], coor[1], coor[2], coor[3], uid))
        print '.'

    fout.close()
Exemplo n.º 2
0
def SSD_detect(filename):
    try:
        img = skimage.io.imread(filename)
        _ssd_fd = FaceDetection.FaceDetection()
        cc, scores, bboxes = _ssd_fd.dectectFace(img)
        res = {}
        if len(scores) < 1:
            res = {'code':config.CODE_NON_FACE}
        else:
            #visualization.bboxes_draw_on_img(img, cc, scores, bboxes, visualization.colors, class_names=['none-face', 'face'])
            #skimage.io.imsave(tmp_filename, img)
            bboxes = normalizeBBoxes(bboxes, img.shape[1], img.shape[0])

            res['code'] = config.CODE_SUCCESS
            res['num'] = len(scores)
            res['coordinates'] = []
            for ii in range(len(scores)):
                if scores[ii] >= config.SCORE_THRES:
                    y1, x1, y2, x2 = bboxes[ii]
                    res['coordinates'].append("%d,%d,%d,%d"%(x1, y1, x2 - x1, y2 - y1))
            res["url"] = filename
    except:
        res = {'code':config.CODE_SYS_ERR}
    return res
Exemplo n.º 3
0
    cv2.imwrite(Image_Pth, image)
    Send_Mail(Image_Pth, "Test Email", "Label")

if (args["dropbox"]):
    print("")
    print("DropBox Test")
    print("")

    link = UploadToDropBox("img.jpg")
    print("File Uploaded, Viewing Link is: " + link)

if (args["mms"]):
    print("")
    print("This test requires the dropbox test is also run using -d")
    print("MMS Test using the file uploaded in the dropbox test")
    print("")
    Send_MMS("Test MMS", ConfigValues.ReturnAlertPhoneDestination(), link)

if (args["facedetection"]):
    print("")
    print("FaceDetection Test")
    print("")
    image = cv2.imread("C:\RT_OD\Couple.jpg")
    #next two lines are only needed to view the test image to validate that it loaded correctly from disk
    #cv2.imshow("Image", image)
    #cv2.waitKey(0)
    FaceDetection.FaceDetection(image)

print("")
print("Test Completed!")
Exemplo n.º 4
0
import FaceDetection
import cv2
import glob
import os, sys, time
import visualization
faceDect = FaceDetection.FaceDetection()

INPUT = '/home/nptai/WIDER_val/images'
OUTPUT = './output-widerface'

paths = glob.glob(os.path.join(INPUT, '*/*.jpg'))
paths.sort()

if not os.path.isdir(OUTPUT):
    os.mkdir(OUTPUT)

total = len(paths)
curr = 0
xxtime = time.time()
for path in paths:
    xtime = time.time()
    curr += 1

    img = cv2.imread(path)
    [w, h, _] = img.shape

    classes, scores, bboxes = faceDect.dectectFace(img)

    visualization.bboxes_draw_on_img(img,
                                     classes,
                                     scores,
Exemplo n.º 5
0
import random
import string

import skimage.io
import numpy as np
import urllib

import config

import sys
sys.path.insert(0, config.SSD300_DIR)
import FaceDetection
import visualization

global gb_detector
gb_detector = FaceDetection.FaceDetection()

def hello(request):
    return HttpResponse('mmHCI Face Detection Webservice')

def handle_uploaded_file(f, filename):
    with open(filename, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

@csrf_exempt
def detect(request):
    tmp_filename = 'media/' + ''.join(random.choice(string.ascii_uppercase 
                        + string.digits) for _ in range(64)) + '.jpg'
    if request.method == 'POST':
        handle_uploaded_file(request.FILES['image'], tmp_filename)
Exemplo n.º 6
0
import FaceDetection

x = FaceDetection.FaceDetection('test.png')
x.startStream()
Exemplo n.º 7
0
import os
import cv2

import FaceDetection as FD

OUT_DIR = '/home/mmhci_hcmus/cropped-avatars'
IMAGES_FILE = '/home/mmhci_hcmus/avatars.txt'

if __name__ == '__main__':
	fi = open(IMAGES_FILE, 'r')
	if not os.path.exists(OUT_DIR):
		os.makedirs(OUT_DIR)
	
	fd = FD.FaceDetection()
	fout = open(OUT_DIR + '.txt', 'w')
	for path in fi:
		path = path.strip()
		#print path
		name = os.path.basename(path).split('.')[0]
		_fd_ =  ''
		outpath = os.path.join(OUT_DIR, _fd_)
		#if os.path.exists(outpath):
		#	continue
		if not os.path.exists(outpath):
			os.mkdir(outpath)
		
		frame = cv2.imread(path)
		try:
			assert(len(frame.shape) == 3)
		except:
			fout.write('%s\t%d\n'%(os.path.basename(path), -1))
Exemplo n.º 8
0
                                                     ROIStartY):(endY +
                                                                 ROIStartY),
                                                    (startX +
                                                     ROIStartX):(endX +
                                                                 ROIStartX)]
                                cv2.imshow("FaceFrame", roiDetected)
                                key = cv2.waitKey(1) & 0xFF

                                #Save Image to Disk
                                cv2.imwrite(Image_Path, roiDetected)
                                #Upload image to dropbox and generate a public sharing URL
                                URL = UploadToDropBox(Image_Name)
                                print("DropBox Image Public Share URL: " +
                                      str(URL))

                                FaceFound = FaceDetection.FaceDetection(
                                    roiDetected)
                                if (FaceFound == 'true'):
                                    FaceDetectionDelay = SMSAlertDelay

                        else:
                            print("")
                            print(
                                "False Detection Occured Detection Percentage: "
                                + str(DectectionPercentage))
                            print("")
                    else:
                        if (ValidObjectDetected == 'true'):
                            #if camera is in cool down period after a detection and the person remains in frame extend the cool down to prevent further alarms
                            SMSAlertDelay = SMSAlertDelay + datetime.timedelta(
                                seconds=0.5)
                            print("Object still in frame, Extending Cool Down")
Exemplo n.º 9
0
    def data_storage_run(self):
        self.image_names = CommonComponents.load_image_names(
            config.WORKING_FOLDER)
        self.activeComponents = [True, True, True, True]
        if self.activeComponents[0]:
            print('Starting yolo detector')
            self.yoloDetector = yolo.ObjectDetector()
        if self.activeComponents[1]:
            print('Starting mask detector')
            self.maskDetector = mask.MaskRCNN()
        if self.activeComponents[2]:
            print('Starting face detector')
            self.faceDetector = face.FaceDetection()
        if self.activeComponents[3]:
            print('Starting pose detector')
            self.poseDetector = pose.PoseDetection()

        #Creates the full set of results in an array style setup
        self.full_results = []
        # Doing a loop over all images in the folder to find all of our results
        for name in self.image_names:
            new_entry = DataStorage.DataStorage(name.name)
            #Adding the yolo results for our entry
            if config.YOLO_OBJECT_COMPARISSON:
                yolo_results = self.yoloDetector.read_image(name.name)
                for object in yolo_results:
                    new_entry.yolo.append(DataStorage.Yolo(object))
            #Adding the mask results for our entry
            if config.FACE_COLOUR_COMPARISSON or config.MASK_OBJECT_COMPARISSON:
                self.maskDetector = mask.MaskRCNN()
                mask_entries = self.maskDetector.read_image(name.name)
                for masking in range(mask_entries[0].__len__()):
                    new_entry.mask_results.append(
                        DataStorage.Mask(mask_entries[0][masking],
                                         mask_entries[1][masking],
                                         mask_entries[2][masking],
                                         mask_entries[3][masking],
                                         mask_entries[4][masking],
                                         mask_entries[5][masking]))
            if config.FACE_COLOUR_COMPARISSON:
                if config.FACE_DETECTION_TYPE == "Cascade":
                    face_entry = self.faceDetector.read_image(name.name)
                    for front_face in face_entry[0]:
                        new_entry.faces.append(
                            DataStorage.Face(front_face, "Front"))
                    for side_face in face_entry[1]:
                        new_entry.faces.append(
                            DataStorage.Face(side_face, "Side"))
                elif config.FACE_DETECTION_TYPE == "dlib":
                    face_entries = self.faceDetector.facial_recognition_library_read_image(
                        name.name)
                    for x in face_entries:
                        new_entry.faces.append(
                            DataStorage.Face(x, "Unconfirmed"))
            if self.activeComponents[3]:
                # In here is where pose detection is done
                poses_detected = self.poseDetector.read_image(name.name)
                new_entry.poses = self.pose_processing(name.name,
                                                       poses_detected)
            self.full_results.append(new_entry)
        # Showing off all the face results here
        if config.DRAW_DISPLAY_IMAGES:
            for entry in self.full_results:
                testing_image = cv.imread(entry.image_name)
                if config.DRAW_FACE_RESULTS:
                    for face_entry in entry.faces:
                        face_entry.draw_face(testing_image, [255, 255, 255])
                if config.DRAW_MASK_RESULTS:
                    for mask_entry in entry.mask_results:
                        mask_entry.draw_mask(testing_image, [255, 255, 255])
                if config.DRAW_POSE_RESULTS:
                    for pose_entry in entry.poses:
                        pose_entry.draw_pose(testing_image)
                if config.FACE_SHADOW_REMOVAL:
                    testing_image = CommonComponents.retinex_shadow_removal(
                        testing_image, config.FACE_SHADOW_REMOVAL_TYPE)
                cv.imshow("Testing image", testing_image)
                cv.waitKey(0)

        # Object similarity scoring methods
        # Yolo scoring
        if config.YOLO_OBJECT_COMPARISSON:
            self.yolo_object_comparisson()
        # Mask scoring
        if config.MASK_OBJECT_COMPARISSON:
            self.mask_object_comparisson()

        # Running a maskless face-colour analysis
        if config.FACE_COLOUR_COMPARISSON:
            self.maskless_face_colour_analysis()
            # Calculating average maskless hsv face colours
            self.maskless_hsv_average_calculation()
            # Running a mask-based face_colour analysis
            self.face_average_colour_detection()
            # Making the comparissons of the face-based colour detections
            self.face_average_colour_comparissons()

        # Running a mask-based clothing colour analysis
        if config.CLOTHING_COLOUR_COMPARISSON:
            self.pose_average_colour_detection_open_pose()
            # Running a face-sized base clothing colour analysis
            self.average_clothes_detection_results_comparing()