示例#1
0
def main():

    if cv2gpu.is_cuda_compatible():
        cv2gpu.init_gpu_detector(cascade_file_gpu)
    else:
        cv2gpu.init_cpu_detector(cascade_file_cpu)
    
    image = cv2.imread(image_file, cv2.IMREAD_COLOR)

    dims = image.shape
    image = image.ravel()

    # Run once it initialize gpu with instructions
    faces = cv2gpu.find_faces(dims, image)

    start = datetime.datetime.now()
    faces = cv2gpu.find_faces(dims, image)

    image = cv2.imread(image_file)
    for (x, y, w, h) in faces:
        print('X: {x}, Y: {y}, width: {w}, height: {h}'.format(x=x, y=y, w=w, h=h))
        #cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
        #cv2.imshow('faces', image)
        #cv2.waitKey(0)
    print('Time processed (s): ' + str(datetime.datetime.now() - start))
示例#2
0
def separate_images(image_obj):

    size_file_max = 200000

    def prune_func_gpu(image_path):
        if getsize(image_path) < size_file_max:
            faces = cv2gpu.find_faces(image_path)
            if faces:
                return len(faces) > 0
        return False

    def prune_func_cpu(image_path):
        if getsize(image_path) < size_file_max:
            image = cv2.imread(image_path, 0)
            faces = cascade.detectMultiScale(image)
            if faces:
                return len(faces) > 0
        return False

    if not isfile(cascade_gpu_path) or not isfile(cascade_cpu_path):
        print '{} or {} is not a file'.format(cascade_gpu_path, cascade_cpu_path)
        sys.exit(1)

    prune_func = None

    if cv2gpu_imported:
        prune_func = prune_func_gpu
        if cv2gpu.is_cuda_compatible():
            print 'Using GPU detector'
            cv2gpu.init_gpu_detector(cascade_gpu_path)
        else:
            print 'Using CPU detector'
            cv2gpu.init_cpu_detector(cascade_cpu_path)
    else:
        prune_func = prune_func_cpu
        cascade = cv2.CascadeClassifier(cascade_cpu_path)

    image_num_max = count_images(image_obj)
    image_num_curr = 0

    for tld in image_obj:
        out_dir = join(processed_dir, tld)
        if not isdir(out_dir):
            makedirs(out_dir)
        images = image_obj[tld]
        for url in images:
            path_orig = images[url]
            path_new = join(out_dir, basename(path_orig))
            print 'Image {} / {}, ({})'.format(image_num_curr, image_num_max, getsize(path_orig))
            image_num_curr += 1
            if not prune_func(path_orig):
                continue
            if not isfile(path_new):
                copy2(path_orig, path_new)
            images[url] = path_new
    return image_obj
def tryFaces(frame, type):
    cv2gpu.init_gpu_detector('cv2\data\haarcascades_cuda\haarcascade_frontalface_alt2.xml')
    framCpy = np.copy(frame)
    faces = cv2gpu.find_faces(image_file)
    for (x, y, w, h) in faces:
        center = (x + w // 2, y + h // 2)
        framCpy = cv2.ellipse(framCpy, center, (w // 2, h // 2), 0, 0, 360, (255, 0, 255), 4)
        # -- In each face, detect eyes
    cv2.imshow(str(type), framCpy)
    framCpy = np.zeros((2,3))
示例#4
0
def main():

    if cv2gpu.is_cuda_compatible():
        cv2gpu.init_gpu_detector(cascade_file_gpu)
    else:
        cv2gpu.init_cpu_detector(cascade_file_cpu)

    faces = cv2gpu.find_faces(image_file)
    image = cv2.imread(image_file)
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.imshow('faces', image)
        cv2.waitKey(0)
示例#5
0
def main():

    if cv2gpu.is_cuda_compatible():
        cv2gpu.init_gpu_detector(cascade_file_gpu)
    else:
        cv2gpu.init_cpu_detector(cascade_file_cpu)
    
    faces = cv2gpu.find_faces(image_file)
    image = cv2.imread(image_file)
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.imshow('faces', image)
        cv2.waitKey(0)
def create_detector(gpu_or_cpu, cascade_cpu, cascade_gpu):
    if not os.path.isfile(cascade_cpu) or not os.path.isfile(cascade_gpu):
        sys.exit('{} or {} is not a file'.format(cascade_cpu, cascade_gpu))
    if cv2gpu.is_cuda_compatible() and gpu_or_cpu == 'gpu':
        sys.stdout.write('Using GPU CascadeClassifier\n')
        cv2gpu.init_gpu_detector(cascade_gpu)
    else:
        sys.stdout.write('Using CPU CascadeClassifier\n')
        cv2gpu.init_cpu_detector(cascade_cpu)

    class Detector(object):
        def detect(self, image_path):
            return cv2gpu.find_faces(image_path)

    return Detector()
    print("Argument parsing and import libraries took {} seconds.".format(
        time.time() - start))
    start = time.time()

align = openface.AlignDlib(args.dlibFacePredictor)
net = openface.TorchNeuralNet(args.networkModel,
                              imgDim=args.imgDim,
                              cuda=args.cuda)
face_cascade = cv2.CascadeClassifier(
    '/root/openface/data/lbpcascades/lbpcascade_frontalface_improved.xml')
#face_cascade = cv2.CascadeClassifier('/root/openface/data/lbpcascades/lbpcascade_profileface.xml')
if face_cascade.empty():
    print("Can not load face cascade classifier xml!")

if cv2gpu.is_cuda_compatible():
    cv2gpu.init_gpu_detector(
        '/root/openface/data/haarcascade_frontalface_default_cuda.xml')
    #cv2gpu.init_gpu_detector('/root/openface/data/lbpcascades/lbpcascade_frontalface_improved.xml')
    print("Using gpu haarcascade!")
else:
    cv2gpu.init_cpu_detector(
        '/root/openface/data/haarcascade_frontalface_default.xml')
    print("Using cpu haarcascade only!")

if args.verbose:
    print("Loading the dlib and OpenFace models took {} seconds.".format(
        time.time() - start))
    start = time.time()


def round_to_1(x):
    if x == 0:
示例#8
0
    def mapper_init(self):
        def load_from_small_dataset(colorferet_small_dir):

            face_labels_str = {
                'Black-or-African-American': 0,
                'Asian': 1,
                'Asian-Middle-Eastern': 2,
                'Hispanic': 3,
                'Native-American': 4,
                'Other': 5,
                'Pacific-Islander': 6,
                'White': 7
            }

            images = []
            labels = []

            for face_label_str in face_labels_str:
                face_label_num = face_labels_str[face_label_str]
                image_dir = os.path.join(colorferet_small_dir, face_label_str)
                image_files = [
                    os.path.join(image_dir, image_file)
                    for image_file in os.listdir(image_dir)
                ]
                images_tmp = [
                    cv2.resize(cv2.imread(image_file, 0), (256, 256))
                    for image_file in image_files
                    if image_file.split('.')[-1] == 'png'
                ]
                labels_tmp = [face_label_num] * len(images_tmp)
                images.extend(images_tmp)
                labels.extend(labels_tmp)

            return images, labels

        self.video_dir = jobconf_from_env('job.settings.video_dir')
        self.output_dir = os.path.join(
            jobconf_from_env('mapreduce.task.output.dir'), 'faces')
        self.opencv_version = int(cv2.__version__.split('.')[0])

        if self.opencv_version == 2:
            self.recognizer = cv2.createLBPHFaceRecognizer()
            # self.recognizer = cv2.createFisherFaceRecognizer()
            # self.recognizer = cv2.createEigenFaceRecognizer()
        elif self.opencv_version == 3:
            self.recognizer = cv2.face.createLBPHFaceRecognizer()
            # self.recognizer = cv2.face.createFisherFaceRecognizer()
            # self.recognizer = cv2.face.createEigenFaceRecognizer()

        if cv2gpu.is_cuda_compatible():
            sys.stderr.write('Using GPU CascadeClassifier')
            cv2gpu.init_gpu_detector(
                jobconf_from_env('job.settings.cascade_gpu'))
        else:
            sys.stderr.write('Using CPU CascadeClassifier')
            cv2gpu.init_cpu_detector(
                jobconf_from_env('job.settings.cascade_cpu'))

        images, labels = load_from_small_dataset(
            jobconf_from_env('job.settings.colorferet'))

        self.recognizer.train(images, numpy.array(labels))
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

        self.face_labels_num = {
            0: 'Black-or-African-American',
            1: 'Asian',
            2: 'Asian-Middle-Eastern',
            3: 'Hispanic',
            4: 'Native-American',
            5: 'Other',
            6: 'Pacific-Islander',
            7: 'White'
        }

        self.write_results = False
示例#9
0
                    default='auto')
parser.add_argument("--alpha", type=float, default=0.1)

args = parser.parse_args()

print("Initializing face detector...")
if args.detector == 'hog':
    detector = dlib.get_frontal_face_detector()
elif args.detector == 'cnn':
    detector = dlib.cnn_face_detection_model_v1(args.cnn_model_path)
elif args.detector == 'opencv':
    detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
elif args.detector == 'cv2gpu':
    import cv2gpu
    if cv2gpu.is_cuda_compatible():
        cv2gpu.init_gpu_detector('haarcascade_frontalface_default_cuda.xml')
    else:
        cv2gpu.init_cpu_detector('haarcascade_frontalface_default.xml')
else:
    assert False, "Unknown detector " + args.detector
predictor = dlib.shape_predictor(args.shape_predictor_path)
facerec = dlib.face_recognition_model_v1(args.face_rec_model_path)

print("Loading feature vectors...")
vecs = np.load(args.vecs_file)
nn = NearestNeighbors(n_neighbors=args.n_neighbors, algorithm=args.algorithm)
nn.fit(vecs)

print("Loading image metadata...")
with open(args.data_file) as csvfile:
    reader = csv.DictReader(
示例#10
0
    def mapper_init(self):

        def load_from_small_dataset(colorferet_small_dir):

            face_labels_str = {
                'Black-or-African-American': 0,
                'Asian': 1,
                'Asian-Middle-Eastern': 2,
                'Hispanic': 3,
                'Native-American': 4,
                'Other': 5,
                'Pacific-Islander': 6,
                'White': 7
            }

            images = []
            labels = []

            for face_label_str in face_labels_str:
                face_label_num = face_labels_str[face_label_str]
                image_dir = os.path.join(colorferet_small_dir, face_label_str)
                image_files = [os.path.join(image_dir, image_file) for image_file in os.listdir(image_dir)]
                images_tmp = [cv2.resize(cv2.imread(image_file, 0), (256, 256)) for image_file in image_files if image_file.split('.')[-1] == 'png']
                labels_tmp = [face_label_num] * len(images_tmp)
                images.extend(images_tmp)
                labels.extend(labels_tmp)

            return images, labels

        self.video_dir = jobconf_from_env('job.settings.video_dir')
        self.output_dir = os.path.join(jobconf_from_env('mapreduce.task.output.dir'), 'faces')
        self.opencv_version = int(cv2.__version__.split('.')[0])

        if self.opencv_version == 2:
            self.recognizer = cv2.createLBPHFaceRecognizer()
            # self.recognizer = cv2.createFisherFaceRecognizer()
            # self.recognizer = cv2.createEigenFaceRecognizer()
        elif self.opencv_version == 3:
            self.recognizer = cv2.face.createLBPHFaceRecognizer()
            # self.recognizer = cv2.face.createFisherFaceRecognizer()
            # self.recognizer = cv2.face.createEigenFaceRecognizer()

        if cv2gpu.is_cuda_compatible():
            sys.stderr.write('Using GPU CascadeClassifier')
            cv2gpu.init_gpu_detector(jobconf_from_env('job.settings.cascade_gpu'))
        else:
            sys.stderr.write('Using CPU CascadeClassifier')
            cv2gpu.init_cpu_detector(jobconf_from_env('job.settings.cascade_cpu'))

        images, labels = load_from_small_dataset(jobconf_from_env('job.settings.colorferet'))

        self.recognizer.train(images, numpy.array(labels))
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

        self.face_labels_num = {
            0: 'Black-or-African-American',
            1: 'Asian',
            2: 'Asian-Middle-Eastern',
            3: 'Hispanic',
            4: 'Native-American',
            5: 'Other',
            6: 'Pacific-Islander',
            7: 'White'
        }

        self.write_results = False