Ejemplo n.º 1
0
def changeFaces(win, center, size):
    grimButton, smileButton, winkButton, frownButton, quitButton = \
    makeButtons(win)
    theFace = Face(win, center, size)
    pt = win.getMouse()
    while not quitButton.clicked(pt):
        if grimButton.clicked(pt):
            cleanSlate(win)
            grimButton, smileButton, winkButton, frownButton, quitButton = \
    makeButtons(win)
            theFace = Face(win, center, size)
        elif smileButton.clicked(pt):
            cleanSlate(win)
            grimButton, smileButton, winkButton, frownButton, quitButton = \
    makeButtons(win)
            theFace.smile(win, center, size)
        elif winkButton.clicked(pt):
            cleanSlate(win)
            grimButton, smileButton, winkButton, frownButton, quitButton = \
    makeButtons(win)
            theFace.smile(win, center, size)
        elif frownButton.clicked(pt):
            cleanSlate(win)
            grimButton, smileButton, winkButton, frownButton, quitButton = \
    makeButtons(win)
            theFace.frown(win, center, size)
        else:
            pass
        pt = win.getMouse()
Ejemplo n.º 2
0
	def detect(self):
		faces = []
		eyes = []
		rgb_green = (0, 255, 0)
		rgb_blue = (0, 0, 255)

		detected_faces = self.__detect_faces()

		for (x, y, w, h) in detected_faces:
			face = Face(self.image, x, y, w, h, rgb_green)
			face.draw(2)
			faces.append(face)
			detected_eyes = self.__detect_eyes(face.data())
			if len(detected_eyes) > 0:
				for(eye_x, eye_y, eye_w, eye_h) in detected_eyes:
					eye = Eye(self.image, face.x + eye_x, face.y + eye_y, eye_w, eye_h, rgb_blue)
					eye.draw(2)
			        eyes.append(eye)

			detected_smile = self.__detect_smile(face.data())
			if len(detected_smile) > 0:
				smileness = detected_smile[0][1]
				smile_text_position = ((x - 15), y + (h + 25))
				if smileness >= 15:
					cv2.putText(self.image, "Smiling: Yes", smile_text_position, cv2.FONT_HERSHEY_DUPLEX, 1, (255,255,255))
				else:
					cv2.putText(self.image, "Smiling: No", smile_text_position, cv2.FONT_HERSHEY_DUPLEX, 1, (255,255,255))

			return { "faces" : faces, "eyes" : eyes}
Ejemplo n.º 3
0
Archivo: test.py Proyecto: gutorc92/unb
def test():
	f = Face()
	pic = "/home/gustavo/Documents/unb/das/joserobertoarruda.jpg"
	img = cv2.imread(pic)
	img = f.detect(img)
	cv2.imshow('frame',img)
	cv2.waitKey()
Ejemplo n.º 4
0
	def addNewFace(self, location):
		fc = Face(self.weights)
		fc.setID(self.faceIDCount)
		self.totalFaceCount += 1
		self.faceIDCount += 1
		fc.setPosition(location)
		self.visibleFaceList.append(fc)
Ejemplo n.º 5
0
 def test_creat_face(self):
     # create a box
     my_face = Face(BRepPrimAPI_MakeSphere(1., 1.).Face())
     assert not my_face.IsNull()
     assert my_face.tolerance == 1e-06
     assert not my_face.is_planar()
     assert my_face.is_trimmed()
Ejemplo n.º 6
0
 def test_creat_face(self):
     # create a box
     my_face = Face(BRepPrimAPI_MakeSphere(1., 1.).Face())
     assert not my_face.IsNull()
     assert my_face.tolerance == 1e-06
     assert not my_face.is_planar()
     assert my_face.is_trimmed()
Ejemplo n.º 7
0
    def _create_faces(self):
        """
        Creates each faces as 'North', 'South', 'East', 'West', 'Top'.
        
        """
        #create each face

        self.faces.append(
            Face('North', self.building_width, self.building_height,
                 Point(1.0, 0.0, 0.0)))
        self.faces.append(
            Face('West', self.building_depth, self.building_height,
                 Point(0.0, 1.0, 0.0)))
        self.faces.append(
            Face('South', self.building_width, self.building_height,
                 Point(-1.0, 0.0, 0.0)))
        self.faces.append(
            Face('East', self.building_depth, self.building_height,
                 Point(0.0, -1.0, 0.0)))
        self.faces.append(
            Face('Top', self.building_width, self.building_depth,
                 Point(0.0, 0.0, -1.0)))

        self.face_count = len(self.faces)

        #Assign each tap to corresponding faces
        for i in range(self.tap_count):
            for j in range(self.face_count):
                if self.taps[i].face == self.faces[j].name:
                    self.faces[j].taps.append(self.taps[i])
Ejemplo n.º 8
0
	def analyzeFrame(self, rects):
		self.pruneFaceList()
		#Case 1
		# if len(rects)>len(self.visibleFaceList):
			# print "case1"
		if len(self.visibleFaceList)>0:
			megaList, breakPoint = self.dualListHelper(self.visibleFaceList, self.notVisibleFaceList, rects)
			assignmentList = [-1]*(len(self.visibleFaceList)+len(self.notVisibleFaceList))
			totalAssigned=0
			visibleFaces = len(self.visibleFaceList)
			totalFaces = len(self.visibleFaceList)+len(self.notVisibleFaceList)
			indices = []

			while totalAssigned < len(rects):
				# print "WHILE"
				# print len(rects)
				index = 0
				highest = 0
				highFaceIndex = 0
				for i in range(len(megaList)):
					if assignmentList[i] == -1:
						currentVal = max(megaList[i])
						# print currentVal
						currentIndex = megaList[i].index(currentVal)
						# print currentIndex not in assignmentList
						if currentVal > highest and currentIndex not in assignmentList and currentVal > self.minRemovalScore:
							highest = currentVal
							index = currentIndex
							highFaceIndex = i
				if highest != 0:
					if highFaceIndex > breakPoint:

						face = self.notVisibleFaceList.pop(highFaceIndex-breakPoint-1)
						self.visibleFaceList.append(face)
						index = len(self.visibleFaceList)-1
					assignmentList[highFaceIndex] = currentIndex
					indices.append(highFaceIndex)
					totalAssigned +=1
				else:
					print "HIGHEST = 0"
					for j in range(len(rects)):
						# print rects
						if j not in assignmentList:
							# print "here"
							face = Face()
							face.id = self.totalFaceCount
							self.totalFaceCount += 1
							self.visibleFaceList.append(face)
							assignmentList.append(j)
							indices.append(len(assignmentList)-1)
							totalAssigned += 1
			# print assignmentList
			self.makeAssignments(assignmentList,rects, indices, visibleFaces)
			for i in range(visibleFaces-1):
				if assignmentList[i] == -1:
					face = self.visibleFaceList.pop(i)
					self.notVisibleFaceList.append(face)
		else:
			for i in range(len(rects)):
				self.addNewFace(rects[i])
Ejemplo n.º 9
0
def demo_video(video_file):
    import time
    facedemo = Face(detector_method=DETECTOR, recognition_method=None)
    cap = common.VideoStream(video_file, queueSize=4).start()
    time.sleep(1)
    total_t, counter = 0, 0
    t = common.clock()

    while not cap.stopped:
        imgcv = cap.read()
        if imgcv is not None:
            counter += 1
            detections = facedemo.detect(imgcv, upsamples=0)
            ids = range(len(detections))

            # temp = mtracker.update(imgcv, to_cvbox(detections))
            # cvboxes, ids = [], []
            # for tid,tracker in mtracker.trackers.items():
            #     if tracker.visible_count > 3 and tracker.consecutive_invisible_count<10:
            #         cvboxes.append(tracker.bbox)
            #         ids.append(tid)
            # detections = to_bbox(cvboxes)

            print(detections)
            common.showImage(common.drawObjects(imgcv, detections, ids))

        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            break

        t1 = common.clock()
        dt = t1 - t
        t = t1
        total_t += dt
        print(counter / total_t)
Ejemplo n.º 10
0
def getFaces(images):
    encs = []
    faces = []
    for n, img in enumerate(images):
        print('Working on image [{}]'.format(n))
        dets, scores, idx = detector.run(img, 1, -0.5)
        print('{} faces detected'.format(len(dets)))
        faces_n = []
        boxes = []
        encs_n = []
        for i, d in enumerate(dets):
            face = Face()
            x1 = d.top(); y2 = d.right(); x2 = d.bottom(); y1 = d.left();
            face.bound_box = (x1, y1, x2, y2)
            boxes.append((x1, y2, x2, y1))
            face.img_id = n
            face.myFace = img[x1:x2, y1:y2]
            faces_n.append(face)
            cv2.rectangle(img, (y1,x1), (y2,x2), (0, 0, 255), 5)
            print('{:.02f}'.format(scores[i]), idx[i], x1, y1, x2, y2)
        encs_n = fr.face_encodings(img, boxes)
        for i, e in enumerate(encs_n):
            faces_n[i].enc = e
            faces.append(faces_n[i])
            encs.append(e)
        plt.imshow(img)
        plt.axis('off')
        plt.show()
    return faces, np.array(encs)
Ejemplo n.º 11
0
 def addNewFace(self, location):
     """create new face object for a newly detected face"""
     fc = Face(self.weights)
     fc.setID(self.faceIDCount)
     self.totalFaceCount += 1
     self.faceIDCount += 1
     fc.setPosition(location)
     self.visibleFaceList.append(fc)
Ejemplo n.º 12
0
 def __init__(self, name, n, length, edgeNames=None, allEdges=None):
   pts = []
   lastpt = (0, 0)
   dt = (2 * pi / n)
   for i in range(n):
     lastpt = (lastpt[0] + cos(i * dt), lastpt[1] + sin(i * dt))
     pts.append(lastpt)
     
   Face.__init__(self, name, pts, edgeNames=edgeNames, allEdges=allEdges)
Ejemplo n.º 13
0
 def playSongAccordingToEmo(self):
     emo = Face()
     happiness, sadness = emo.getEmo(self.key, self.url)
     #print(happiness)
     #print(sadness)
     crawler = YTCrawler()
     if happiness >= sadness:
         crawler.retrieve_vids("happy songs")
     else:
         crawler.retrieve_vids("sad songs")
Ejemplo n.º 14
0
 def __init__(self, images, feature_points=None, write=None):
     Face.__init__(self, np.zeros(images[0].shape))
     self.images = [Face(img, feature_points) for img in images]
     self.textures = []
     self.frames = []
     self.all_features = np.zeros((74, len(images), 2))
     self.write = write
     if self.write:
         if not os.path.exists(self.write):
             os.makedirs(self.write)
Ejemplo n.º 15
0
 def get_faces(self):
     face_haarcascade_path = 'haarcascades/haarcascade_frontalface_default.xml'
     detector = cv2.CascadeClassifier(face_haarcascade_path)
     detected = []
     gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
     faces = detector.detectMultiScale(gray)
     for (x, y, w, h) in faces:
         face = Face(self.image, y, x + w, y + h, x)
         if face.is_it_a_face():
             detected.append(face)
     return detected
Ejemplo n.º 16
0
    def create_face(self):
        face = Face()
        self.fCount += 1
        face.num = self.fCount

        if self.firstF is None:
            self.firstF = face
        if self.lastF is not None:
            self.lastF.next = face
        self.lastF = face

        return face
Ejemplo n.º 17
0
 def __init__(self, label, clf):
     self.frame = None
     self.thread1 = None
     self.thread2 = None
     self.stopEvent1 = None
     self.stopEvent2 = None
     self.started = None
     self.captured = None
     self.label = label
     self.vs = VideoStream().start()
     self.fa = Face()
     self.emotion = Emotion(clf)
     self.outputPath = None
Ejemplo n.º 18
0
def face_orientation(blobs: List[Blob], face: Face, threshold: float) -> Face:
    """
    Returns the well oriented face
    """

    p = face.v1 + face.normal()
    p.energy = calc_energy(blobs, p)

    if p.energy < threshold:
        return face
    else:
        face.v1, face.v3 = face.v3, face.v1

        return face
Ejemplo n.º 19
0
    def __init__(self):
        self.f = Face()
        self.net = get_model(10, True)
        ckpt = torch.load("weights/arcface.pth",
                          map_location=torch.device("cpu"))
        self.net.load_state_dict(ckpt)
        self.net.eval()

        self.transform = tf.Compose([
            tf.Resize((112, 112)),
            tf.ToTensor(),
            tf.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
        ])
        self.load()
Ejemplo n.º 20
0
    def __init__(self, resolution, local_up):
        positions = []
        faces = []

        axis_a = Vec3d(local_up.y, local_up.z, local_up.x)
        axis_b = local_up.cross(axis_a)
        for y in range(resolution):
            for x in range(resolution):
                i = x + y * resolution
                percent = Vec3d(x, y, 0) / (resolution - 1)
                vector_on_unit_cube = local_up + (
                    axis_a *
                    (percent.x - .5) * 2) + (percent.y - .5) * 2 * axis_b
                point_on_unit_cube = Point(vector_on_unit_cube.x,
                                           vector_on_unit_cube.y,
                                           vector_on_unit_cube.z)

                point_on_unit_sphere = point_on_unit_cube.normalized
                positions.append(point_on_unit_sphere)
                if x is not resolution - 1 and y is not resolution - 1:
                    faces.append(
                        Face([
                            i, i + resolution + 1, i + resolution, i, i + 1,
                            i + resolution + 1
                        ]))

        super().__init__(positions, faces)
Ejemplo n.º 21
0
 def add_containing_face_to_dcel():
     containing_face_edges = [
         edge for edge in dcel.edges if not edge.nxt
     ]
     edge = containing_face_edges.pop()
     face = Face(outer_component=None, inner_components=[edge])
     dcel.faces.append(face)
     first_edge = edge
     previous_edge = [
         e for e in containing_face_edges
         if e.get_destination() == edge.origin
     ]
     edge.prev = previous_edge[0]
     while len(containing_face_edges) > 1:
         edge.incident_face = face
         next_edge = [
             e for e in containing_face_edges
             if e.origin == edge.get_destination()
         ]
         edge.nxt = next_edge[0]
         next_edge[0].prev = edge
         edge = next_edge[0]
         containing_face_edges.remove(next_edge[0])
     edge_2 = containing_face_edges.pop()
     edge.incident_face = face
     edge_2.incident_face = face
     edge_2.prev = edge
     edge_2.nxt = first_edge
     edge.nxt = edge_2
Ejemplo n.º 22
0
def face(index=0, fit=True, N=67, K=12, interpolation=True):
    from Absfile import AbsFile
    from face import Face
    import algorithms

    file = ['test_16/04371d164.abs', 'test_same/04203d350.abs', 'test_same/04203d352.abs', 'test_same/04203d354.abs',
            'test_8/04316d216.abs', 'test_4/04374d193.abs'][index]
    face = Face(AbsFile(file))

    if interpolation:
        algorithms.repair(face)

    algorithms.smooth(face)
    algorithms.crop(face)
    algorithms.zoom(face)
    algorithms.key_points(face)
    algorithms.rotate(face)

    if fit:
        algorithms.key_points(face)
        algorithms.fit(face)

    # Extract features
    algorithms.features_histogram(face, N, K)

    return face
Ejemplo n.º 23
0
    def makeFaces (self):
        with open ('faces.txt') as file:
            str= ""
            for line in file:
                if "---" not in line:
                    str+= line
                else:
                    arr = str.split()
                    #print(arr)
                    name = arr[0]
                    delay = arr[1]
                    node1str = arr[2]
                    if self.producers.__contains__(node1str):
                        node1 = self.producers[node1str]
                    else:
                        node1 = self.consumers[node1str]
                    node2str = arr[3]
                    if self.producers.__contains__(node2str):
                        node2 = self.producers[node2str]
                    else:
                        node2 = self.consumers[node2str]

                    #print "newFace -->" , name , node1.name , node2.name
                    newFace = Face (name , delay , node1 , node2)
                    self.faces[name] = newFace
                    str = ""
Ejemplo n.º 24
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "Program to create timelapses of faces using facial landmark detection."
    )
    parser.add_argument('images',
                        metavar='i',
                        help='Path to folder containing images')
    parser.add_argument('-o', '--output', help='name of output video')
    parser.add_argument('-s',
                        '--speed',
                        type=int,
                        default=100,
                        help='milliseconds between frames in timelapse')

    args = parser.parse_args()

    faceList = []

    for file in os.listdir(args.images):
        if file.endswith(".jpg"):
            temp_Image = Image(args.images + "/" + file)
            faceList.append(Face(temp_Image))

    for face in faceList:
        face.detectFeatures()
        #face.show()
        print(face.left_eye)
        print(face.right_eye)
        print(face.eye_midpoint)
        print(face.nose)
Ejemplo n.º 25
0
    def refine_by_delaunay(self, triangles):
        """refines given elements by the delaunay refinement method"""
        p = self.node_list
        t = self.face_list

        for tr in triangles:
            pmid = (p[t[tr][0]] + p[t[tr][1]] + p[t[tr][2]]) / 3
            p = np.append(p, [pmid], axis=0)

        self.edge_length /= 2
        dp = self.edge_length

        for i in range(1, int(ceil(1 / dp))):
            p = np.append(p, [[i * dp, 0]], axis=0)
        for i in range(int(ceil(.5 / dp))):
            p = np.append(p, [[1, i * dp]], axis=0)
        for i in range(int(ceil(.5 / dp))):
            p = np.append(p, [[1 - i * dp, .5]], axis=0)
        for i in range(int(ceil(.5 / dp))):
            p = np.append(p, [[.5, .5 + i * dp]], axis=0)
        for i in range(int(ceil(.5 / dp))):
            p = np.append(p, [[.5 - i * dp, 1]], axis=0)
        for i in range(int(ceil(1 / dp))):
            p = np.append(p, [[0, 1 - i * dp]], axis=0)

        p = unique2d(p)

        t = spspatial.Delaunay(p).vertices
        # remove triangles where centroid outside boundary (good enough...)
        pmid = p[t].sum(1) / 3
        t = t[self.fd(pmid) < 1e-15]

        t = [Face(t[i]) for i in range(len(t))]
        self.node_list = p
        self.face_list = t
Ejemplo n.º 26
0
def bulk(character):
    data = request.form
    ids = json.loads(data.get('ids'))
    for id in ids:
        query = Face.update(character = character).where(Face.id == id)
        query.execute()
    return "success"
def get_faces_with_ids(path_to_db, verbose=False):
    face_id_multiple_pattern = re.compile(".+[1-9]+\.[a-z]{3}")
    faces = []
    for root, dirs, _ in os.walk(path_to_db):
        for dir in dirs:
            path_to_subject = os.path.join(path_to_db, dir)
            for _, _, imgs in os.walk(path_to_subject):
                for img_file in imgs:
                    if verbose:
                        print('Processing subject {} => {}'.format(
                            dir, img_file))
                    if face_id_multiple_pattern.match(img_file) is not None:
                        continue

                    try:
                        face = Face.from_image_path_with_id(
                            os.path.join(path_to_subject, img_file), dir)
                    except Exception as e:
                        face = None
                        if verbose:
                            print(e.message)
                    if face is not None:
                        faces.append(face)

                break

        break

    return faces
Ejemplo n.º 28
0
    def __init__(self, timer, pid_file, debug, time_out, is_daemon):
        self.need_break = False
        self.is_daemon = is_daemon
        self.timer = timer
        self.pid_file = pid_file
        self.debug = debug
        self.time_out = time_out
        self.time = 0;
        self.is_exit_alarm = 0;

        # Устанавливаю обработчики сигналов
        sh = SignalHandler(self)
        signal.signal(signal.SIGTERM, sh.handle_sigterm)
        signal.signal(signal.SIGALRM, sh.handle_sigalarm)
        # Устанавливаем таймер
        signal.setitimer(signal.ITIMER_REAL, timer, timer)

        if self.is_daemon is True:
            # os.chdir("/") 
            os.close(0)   # close C's stdin stream
            os.close(1)   # close C's stdout stream
            os.close(2)
            os.setsid() 
            os.umask(0) 
        
            pid = os.getpid()

            fd = open(self.pid_file, 'w')
            fd.write(str(pid))
            fd.close()

        syslog.openlog( 'Facedetect', 0, syslog.LOG_LOCAL4 )
        self.face = Face(debug)
Ejemplo n.º 29
0
    def _init_face(self):
        """Set up the face"""
        canvasFrame = Frame(self.root)
        canvasFrame.grid(row=1, column=1, padx=5, pady=5)
        self.canvas = Canvas(canvasFrame, width=400, height=400)
        self.canvas.grid(row=1, column=1)

        self.face = Face(self.canvas)
Ejemplo n.º 30
0
    def get_surface_faces(self):
        '''Get the faces from the surface mesh using the ModelFaceID data array.
     
           The faces are vtkPolyData objects with cell data arrays.
        '''
        self.logger.info("========== get_surface_faces ==========")
        face_ids = self.surface.GetCellData().GetArray(
            VtkDataNames.ModelFaceID)
        if face_ids == None:
            self.logger.error("No ModelFaceID data.")
            return
        face_ids_range = 2 * [0]
        face_ids.GetRange(face_ids_range, 0)
        min_id = int(face_ids_range[0])
        max_id = int(face_ids_range[1])
        self.logger.info("Face IDs range: {0:d} {1:d}".format(min_id, max_id))

        ## Extract face geometry.
        #
        mesh_faces = {}

        for i in range(min_id, max_id + 1):
            #print("[Mesh.get_surface_faces] ---------- ID {0:d} ---------".format(i))
            threshold = vtk.vtkThreshold()
            threshold.SetInputData(self.surface)
            threshold.SetInputArrayToProcess(0, 0, 0, 1,
                                             VtkDataNames.ModelFaceID)
            threshold.ThresholdBetween(i, i)
            threshold.Update()

            surfacer = vtk.vtkDataSetSurfaceFilter()
            surfacer.SetInputData(threshold.GetOutput())
            surfacer.Update()
            mesh_faces[i] = Face(i, surfacer.GetOutput())
            #print("Mesh.[get_surface_faces] Face number of points: %d" % mesh_faces[i].GetNumberOfPoints())
            #print("Mesh.[get_surface_faces] Face number of cells: %d" % mesh_faces[i].GetNumberOfCells())
            #write_surface_mesh("surface", mesh_faces[i], str(i))
        #_for i in range(min_id, max_id+1)

        self.boundary_faces = mesh_faces
        center = [0.0, 0.0, 0.0]
        total_num_pts = 0
        for fid, face in self.boundary_faces.items():
            npts = face.surface.GetNumberOfPoints()
            ncells = face.surface.GetNumberOfCells()
            self.logger.info("  id:{0:d} num cells: {1:d}".format(
                face.model_face_id, ncells))
            for i in range(0, npts):
                point = face.surface.GetPoint(i)
                center[0] += point[0]
                center[1] += point[1]
                center[2] += point[2]
            total_num_pts += npts
        center[0] /= total_num_pts
        center[1] /= total_num_pts
        center[2] /= total_num_pts
        self.center = center
Ejemplo n.º 31
0
def generate_cube(order: int = 3) -> Cube:
    faces: Dict[str, Face] = {}
    layers: List[str] = ["TOP", "BOTTOM", "LEFT", "RIGHT", "FRONT", "BACK"]
    for i in range(6):
        matrix: np.matrix = np.array(list([[i] * order] * order))
        face = Face(i, order, order, matrix)
        faces[layers[i]] = face
    cube_returned: Cube = Cube(order, faces)
    return cube_returned
Ejemplo n.º 32
0
    def catmull(self):
        self.meshMemory.append(
            Mesh(self.vertexTable, self.edgeTable, self.faceTable))

        newFaceTablePositions = []

        vertexTable = []
        faceTable = []
        edgeTable = []

        for faceObj in self.faceTable:
            new_faces = self.findNewFacesFromFace(faceObj)  #position list

            for facePos in new_faces:

                v1 = Vertex(facePos[0])
                v2 = Vertex(facePos[1])
                v3 = Vertex(facePos[2])
                v4 = Vertex(facePos[3])

                vertexTable.extend([v1, v2, v3, v4])

                v1 = self.getVertexFromTheTable(v1, vertexTable)
                v2 = self.getVertexFromTheTable(v2, vertexTable)
                v3 = self.getVertexFromTheTable(v3, vertexTable)
                v4 = self.getVertexFromTheTable(v4, vertexTable)

                face = Face([v1, v2, v3, v4])

                v1.addFace(face)
                v2.addFace(face)
                v3.addFace(face)
                v4.addFace(face)

                edge1 = Edge(v1, v2)
                edge2 = Edge(v2, v3)
                edge3 = Edge(v3, v4)
                edge4 = Edge(v1, v4)

                v1.addEdge(edge1, edge4)
                v2.addEdge(edge1, edge2)
                v3.addEdge(edge2, edge3)
                v4.addEdge(edge3, edge4)

                faceTable.append(face)
                edgeTable.append(edge1)
                edgeTable.append(edge2)
                edgeTable.append(edge3)
                edgeTable.append(edge4)

            newFaceTablePositions.extend(new_faces)

        self.faceTable = faceTable
        self.edgeTable = edgeTable
        self.vertexTable = vertexTable

        return newFaceTablePositions
Ejemplo n.º 33
0
def create_face(line):
    values = line.split()

    if len(values) is 5:  # Quads
        return Face([
            int(values[4]) - 1,
            int(values[3]) - 1,
            int(values[2]) - 1,
            int(values[4]) - 1,
            int(values[2]) - 1,
            int(values[1]) - 1
        ])
    elif len(values) is 4:  # Triangles
        return Face(
            [int(values[1]) - 1,
             int(values[2]) - 1,
             int(values[3]) - 1])
    else:
        raise ValueError(f"Invalid face definition {line}")
Ejemplo n.º 34
0
def getFaces(images, n=-1):
    '''
        images :: tuple(name, numpy array)
        n :: ground_truth number of faces in an image
        '''

    faces = []
    possible_people = []
    for img in images:
        print("Working on new image")
        fls = fr.face_locations(img[1], model='hog')
        encs = fr.face_encodings(img[1], fls)
        if len(fls) == 0:
            print("GOT NO FACES IN IMAGE")
        if (len(fls) == n):
            start = len(faces)
            end = start + n
            possible_people.append(list(range(start, end)))
        print(len(encs), len(fls))
        b = 1
        fig, ax = plt.subplots(1)
        ax.imshow(img[1])
        for (fl, enc) in zip(fls, encs):
            face = Face()
            face.bound_box = fl
            face.img_name = img[0]
            face.box_no = b
            b += 1
            face.enc = enc
            faces.append(face)
            tlx, tly, brx, bry = fl
            #x1, y2, x2, y1
            x1 = tlx
            x2 = brx
            y1 = bry
            y2 = tly
            face.myFace = img[1][x1:x2, y1:y2]
            #print(x1,y1,x2,y2)
            if len(fls) > -1:
                cv2.rectangle(img[1], (y1, x1), (y2, x2), (0, 0, 255), 5)
            rect = patches.Rectangle((x1, y1), (x2 - x1), (y2 - y1),
                                     linewidth=2,
                                     edgecolor='b')
            #ax.add_patch(rect)
        if len(fls) > -1:
            y = cv2.resize(np.array(img[1]), (0, 0), fx=0.4, fy=0.4)
            cv2.imshow('disp', y)
            cv2.waitKey(1)
            #plt.show()
        #cv2.imshow(img[0], img[1])
        #cv2.waitKey()
        #cv2.destroyAllWindows()
    if (possible_people):
        return faces, possible_people[0]
    else:
        print("NO IMAGE WITH ALL PHOTOS")
        #exit(0)
        return faces, possible_people
Ejemplo n.º 35
0
 def set_mesh(self, nodes, faces=None):
     """nodes in coordinates, faces in indices"""
     self.node_list = np.array(nodes.copy())
     if faces is not None:
         self.face_list = np.array([
             Face(
                 face,
                 compute_diameter(nodes[face[0]], nodes[face[1]],
                                  nodes[face[2]]), -1) for face in faces
         ])
Ejemplo n.º 36
0
def index_id(id):
    if request.method == 'POST':
        data = request.form
        c = data.get('character')
        if c and c != config["skip_tag"]:
            print(c)
            query = Face.update(character = c).where(Face.id == id)
            query.execute()
        next_id = int(id) + 1
        return redirect(url_for("index_id", id = next_id))

    # get
    else:
        next_face = Face.select().where(Face.id == id).first()
        if not next_face:
            return redirect(url_for("finish"))

        progress = round(Face.select().where(Face.character != None).count() * 100 / Face.select().count(), 2)
        return render_template('index.html', face=next_face, progress=progress, config=config)
Ejemplo n.º 37
0
def get_faces(blobs: List[Blob], tetrahedrons: List[List[Vertex]], threshold: float) -> Tuple[List[Face], List[Vertex]]:
    """
    Returns a list containing all faces defining the surface to draw
    """

    faces, vertices = [], []
    for tetrahedron in tetrahedrons:
        surface_points = get_surface_points(tetrahedron, threshold)

        if surface_points:
            faces.append(face_orientation(blobs, Face(surface_points[0], surface_points[1], surface_points[2]), threshold))

            if len(surface_points) > 3:
                faces.append(face_orientation(blobs, Face(surface_points[1], surface_points[2], surface_points[3]), threshold))

            for vertex in surface_points:
                vertices.append(vertex)

    return faces, vertices
Ejemplo n.º 38
0
    def split_face(self, face, point):
        self.faces.remove(face)
        [e1, e2, e3] = face.edges
        [a, b, c] = face.vertices
        a1 = Edge()
        a2 = Edge()
        b1 = Edge()
        b2 = Edge()
        c1 = Edge()
        c2 = Edge()

        v = Vertex(point, a2)

        f1 = Face(a2)
        f2 = Face(b2)
        f3 = Face(c2)

        e1.next = b1
        e1.prev = a2
        e1.face = f1
        e2.next = c1
        e2.prev = b2
        e2.face = f2
        e3.next = a1
        e3.prev = c2
        e3.face = f3

        # setAttributes(origin, twin, face, next, prev):
        a1.setAttributes(a, a2, f3, c2, e3)
        a2.setAttributes(v, a1, f1, e1, b1)
        b1.setAttributes(b, b2, f1, a2, e1)
        b2.setAttributes(v, b1, f2, e2, c1)
        c1.setAttributes(c, c2, f2, b2, e2)
        c2.setAttributes(v, c1, f3, e3, a1)

        self.vertices.append(v)
        self.edges.extend([a1, a2, b1, b2, c1, c2])
        self.faces.extend([f1, f2, f3])

        return [v, [a1, a2, b1, b2, c1, c2], [f1, f2, f3]]

        self.updated = True
Ejemplo n.º 39
0
    def find_faces(self, image_raw):
        st = log.get_current_time()
        faces = []
        image_small = cv2.resize(
            image_raw, (0, 0),
            fx=settings.RESIZE_FACTOR,
            fy=settings.RESIZE_FACTOR)
        bounding_boxes, _ = align.detect_face.detect_face(
            image_small, self.minsize, self.pnet, self.rnet, self.onet,
            self.threshold, self.factor)
        _factor = int(1 / settings.RESIZE_FACTOR)
        for bb in bounding_boxes:
            face = Face()
            face.image_raw = image_raw
            face.bounding_box = np.zeros(4, dtype=np.int32)

            img_size = np.asarray(image_small.shape)[0:2]
            face.bounding_box[0] = np.maximum(
                bb[0] - self.face_crop_margin / 2, 0)
            face.bounding_box[1] = np.maximum(
                bb[1] - self.face_crop_margin / 2, 0)
            face.bounding_box[2] = np.minimum(
                bb[2] + self.face_crop_margin / 2, img_size[1])
            face.bounding_box[3] = np.minimum(
                bb[3] + self.face_crop_margin / 2, img_size[0])
            cropped = image_small[face.bounding_box[1]:face.bounding_box[3],
                                  face.bounding_box[0]:face.bounding_box[2], :]
            raw_cropped = image_raw[face.bounding_box[1]*_factor:face.bounding_box[3]*_factor,
                                     face.bounding_box[0]*_factor:face.bounding_box[2]*_factor, :]
            face.image = misc.imresize(
                cropped, (self.face_crop_size, self.face_crop_size),
                interp='bilinear')
            face.face_image_raw = misc.imresize(
                raw_cropped, (self.face_crop_size, self.face_crop_size),
                interp='bilinear')
            face.result.timestamp = log.get_current_time()
            faces.append(face)

        et = log.get_current_time()
        log.logging.debug('face num: ' + str(len(faces)) + ' time usage:' +
                          str(et - st) + 'ms')
        return faces
Ejemplo n.º 40
0
def detail():
    if not "pic_path" in request.query:
        response.status = 400
        return "'pic_path' parameter not found"

    pic_path = request.query["pic_path"]

    faces = Face.select().where(Face.pic_path == pic_path)

    if not faces.exists():
        response.status = 404
        return "pic_path '{0}' not found".format(html.escape(pic_path))

    return template("detail.html", pic_path = pic_path)
Ejemplo n.º 41
0
def detail_api():
    if not "pic_path" in request.query:
        response.status = 400
        return { "error": "'pic_path' parameter not found" }

    pic_path = request.query["pic_path"]

    faces = Face.select().where(Face.pic_path == pic_path)

    if not faces.exists():
        response.status = 404
        return { "error": "pic_path '{0}' not found".format(html.escape(pic_path)) }

    return { 
            "faces": [_face_to_dict(x) for x in faces],
            "thumb_url": _build_url(faces[0].thumb_path)
            }
Ejemplo n.º 42
0
from PIL import Image
import numpy as np

from face import Face

import characters
import os

faces = Face.select()

def export(ran, filename):
    os.remove(filename)
    with open(filename, "a") as f:
        for i in ran:
            print (i)
            face = faces[i]
            im = Image.open(face.face_path).resize((124,124))
            im = (np.array(im))
            r = im[:,:,0].flatten()
            g = im[:,:,1].flatten()
            b = im[:,:,2].flatten()
            character_id = characters.search_id(face.character)
            print(character_id)
            label = [character_id]
            out = list(label) + list(r) + list(g) + list(b)
            np.array(out, np.uint8).tofile(f)


face_count = Face.select().count()
face_count_6 = int(face_count / 6)
BASE_DIR = "data/"
Ejemplo n.º 43
0
	def analyzeFrame3(self,rects):
		self.pruneFaceList()
		if len(rects)>len(self.visibleFaceList):
			if len(self.visibleFaceList)>0:
				megaList = self.listHelper(self.visibleFaceList,rects)
				# print megaList
				assignmentList = []
				for i in range(len(megaList)):
					highest = 0
					index = 0
					for j in range(len(megaList[i])):
						# ensure that face hasn't been used already
						if megaList[i][j] >= highest and j not in assignmentList:
							index = j
							highest = megaList[i][j]
					assignmentList.append(index)

				self.makeAssignments(assignmentList, rects)

				notList = self.listHelper(self.notVisibleFaceList,rects)

				if notList != []:
					for i in range(len(rects)):
						index = -1
						highest = 0
						for j in range(len(self.notVisibleFaceList)):
							if j not in assignmentList:
							# print notList
								if notList[i][j] > highest:
									index = j
									highest = notList[j][i]
						if index != -1:
							if notList[index][i] > self.minRemovalScore:
								face = self.notVisibleFaceList.pop(index)
								face.setPosition(rects[i])
								self.visibleFaceList.append(face)
						else:
							fc = Face()
							fc.id = self.totalFaceCount
							# print fc.id
							self.totalFaceCount += 1
							fc.setPosition(rects[i])
							self.visibleFaceList.append(fc)
				else:
					for i in range(len(rects)):
						fc = Face()
						fc.id = self.totalFaceCount
						# print fc.id
						self.totalFaceCount += 1
						fc.setPosition(rects[i])
						self.visibleFaceList.append(fc)
			else:
				for i in range(len(rects)):
					fc = Face()
					fc.id = self.totalFaceCount
					# print fc.id
					self.totalFaceCount += 1
					fc.setPosition(rects[i])
					self.visibleFaceList.append(fc)


		elif len(rects)==len(self.visibleFaceList):
			megaList = self.listHelper(self.visibleFaceList,rects)
			# print megaList
			assignmentList = []
			for i in range(len(megaList)):
				highest = 0
				index = 0
				for j in range(len(megaList[i])):
					if megaList[i][j] >= highest and j not in assignmentList:
						index = j
						highest = megaList[i][j]
				assignmentList.append(index)
			
			self.makeAssignments(assignmentList, rects)

		else:
			# less rects than faces
			megaList = self.listHelper(self.visibleFaceList,rects)
			# print megaList
			assignmentList = []
			probabilityList = []
			for i in range(len(megaList)):
				highest = 0
				index = 0
				for j in range(len(megaList[i])):
					if megaList[i][j] >= highest and j not in assignmentList:
						index = j
						highest = megaList[i][j]
				assignmentList.append(index)
				probabilityList.append(highest)

			if len(probabilityList)!=0:
				lowIndex = probabilityList.index(min(probabilityList))
				self.notVisibleFaceList.append(self.visibleFaceList.pop(lowIndex))
				assignmentList.pop(lowIndex)
				self.makeAssignments(assignmentList, rects)
Ejemplo n.º 44
0
	def analyzeFrame2(self, rects):
		self.pruneFaceList()
		#Case 1
		if len(rects)>len(self.visibleFaceList):
			# print "case1"
			if len(self.visibleFaceList)>0:
				megaList, breakPoint = self.dualListHelper(self.visibleFaceList, self.notVisibleFaceList, rects)
				assignmentList = []
				for i in range(len(megaList)):
					highest = 0
					index = 0
					for j in range(len(megaList[i])):
						# ensure that face hasn't been used already
						if megaList[i][j] >= highest and j not in assignmentList:
							index = j
							highest = megaList[i][j]
					if highest > self.minRemovalScore:
						if i > breakPoint:
							face = self.notVisibleFaceList.pop(i-breakPoint-1)
							self.visibleFaceList.append(face)
							index = len(self.visibleFaceList)-1
						assignmentList.append(index)
					else:
						face = Face()
						face.id = self.totalFaceCount
						self.totalFaceCount += 1
						self.visibleFaceList.append(face)
						assignmentList.append(len(self.visibleFaceList)-1)

				self.makeAssignments(assignmentList, rects)
				k = 0
				while k < breakPoint:
					if k not in assignmentList:
						face = self.visibleFaceList.pop(k)
						self.notVisibleFaceList.append(face)
					k+=1

			else:
				for i in range(len(rects)):
					self.addNewFace(rects[i])

		#Case 2
		elif len(rects)==len(self.visibleFaceList):
			# print "case2"
			megaList, breakPoint = self.dualListHelper(self.visibleFaceList, self.notVisibleFaceList, rects)
			assignmentList = []
			# print "list"
			# print megaList
			for i in range(len(megaList)):
				highest = 0
				index = 0
				for j in range(len(megaList[i])):
					# ensure that face hasn't been used already
					if megaList[i][j] >= highest and j not in assignmentList:
						index = j
						highest = megaList[i][j]
				if highest > self.minRemovalScore:
					# print "problem case?"
					if i > breakPoint:
						face = self.notVisibleFaceList.pop(i-breakPoint-1)
						self.visibleFaceList.append(face)
						index = len(self.visibleFaceList)-1
					assignmentList.append(index)
				else:
					face = Face()
					face.id = self.totalFaceCount
					self.totalFaceCount += 1
					self.visibleFaceList.append(face)
					assignmentList.append(len(self.visibleFaceList)-1)

			self.makeAssignments(assignmentList, rects)
			k = 0
			while k < breakPoint:
				if k not in assignmentList:
					face = self.visibleFaceList.pop(k)
					self.notVisibleFaceList.append(face)
				k+=1

		#Case 3 (less rects than faces)
		else:
			# print "case3"
			megaList, breakPoint = self.dualListHelper(self.visibleFaceList, self.notVisibleFaceList, rects)
			assignmentList = []
			probabilityList = []
			for i in range(len(megaList)):
				highest = 0
				index = 0
				for j in range(len(megaList[i])):
					# ensure that face hasn't been used already
					if megaList[i][j] >= highest and j not in assignmentList:
						index = j
						highest = megaList[i][j]
				probabilityList.append(highest)
				if highest > self.minRemovalScore:
					if i > breakPoint:
						face = self.notVisibleFaceList.pop(i-breakPoint-1)
						self.visibleFaceList.append(face)
						index = len(self.visibleFaceList)-1
					assignmentList.append(index)
				else:
					face = Face()
					face.id = self.totalFaceCount
					self.totalFaceCount += 1
					self.visibleFaceList.append(face)
					assignmentList.append(len(self.visibleFaceList)-1)

			self.makeAssignments(assignmentList, rects)
			k = 0
			while k < breakPoint:
				if k not in assignmentList:
					face = self.visibleFaceList.pop(k)
					self.notVisibleFaceList.append(face)
				k+=1
			l = 0
Ejemplo n.º 45
0
def index():
    next_face = Face.select().where(Face.character == None).first()
    if next_face:
        return redirect(url_for("index_id", id = next_face.id))
    else:
        return redirect(url_for("finish"))
Ejemplo n.º 46
0
def list(character):
    faces = Face.select().where(Face.character == character)
    return render_template('list.html', faces=faces, config=config)
Ejemplo n.º 47
0
 def __init__(self, name, l, w, edgeNames=None, allEdges=None):
   Face.__init__(self, name, ((l, 0), (0, w), (0,0)), edgeNames=edgeNames, allEdges=allEdges)
Ejemplo n.º 48
0
cornerH = Corner('yellow','red', 'blue')

edgeA = Edge('white', 'red')
edgeB = Edge('white', 'green')
edgeC = Edge('white', 'orange')
edgeD = Edge('white', 'blue')
edgeE = Edge('yellow', 'orange')
edgeF = Edge('yellow', 'green')
edgeG = Edge('yellow', 'red')
edgeH = Edge('yellow', 'blue')
edgeI = Edge('orange', 'blue')
edgeJ = Edge('orange', 'green')
edgeK = Edge('red', 'green')
edgeL = Edge('red', 'blue')

white = Face('white', cornerA, cornerB, cornerC, cornerD, edgeA, edgeB, edgeC, edgeD)
yellow = Face('yellow', cornerE, cornerF, cornerG, cornerH, edgeE, edgeF, edgeG, edgeH)
orange = Face('orange', cornerD, cornerC, cornerF, cornerE, edgeC, edgeJ, edgeE, edgeI)
red = Face('red', cornerB, cornerA, cornerH, cornerG, edgeA, edgeL, edgeG, edgeK)
green = Face('green', cornerC, cornerB, cornerG, cornerF, edgeB, edgeK, edgeF, edgeJ)
blue = Face('blue', cornerA, cornerD, cornerE, cornerH, edgeD, edgeI, edgeH, edgeL)
Faces = [white, yellow, orange, red, green, blue]


'''
Use this space to test anything:
'''

white.rotateCW
green.rotateCCW
blue.rotateCW
Ejemplo n.º 49
0
class Daemon:
    def __init__(self, timer, pid_file, debug, time_out, is_daemon):
        self.need_break = False
        self.is_daemon = is_daemon
        self.timer = timer
        self.pid_file = pid_file
        self.debug = debug
        self.time_out = time_out
        self.time = 0;
        self.is_exit_alarm = 0;

        # Устанавливаю обработчики сигналов
        sh = SignalHandler(self)
        signal.signal(signal.SIGTERM, sh.handle_sigterm)
        signal.signal(signal.SIGALRM, sh.handle_sigalarm)
        # Устанавливаем таймер
        signal.setitimer(signal.ITIMER_REAL, timer, timer)

        if self.is_daemon is True:
            # os.chdir("/") 
            os.close(0)   # close C's stdin stream
            os.close(1)   # close C's stdout stream
            os.close(2)
            os.setsid() 
            os.umask(0) 
        
            pid = os.getpid()

            fd = open(self.pid_file, 'w')
            fd.write(str(pid))
            fd.close()

        syslog.openlog( 'Facedetect', 0, syslog.LOG_LOCAL4 )
        self.face = Face(debug)


    def run(self):
        try:
            syslog.syslog( '=== %s ===' % 'Start' )
            while self.need_break is False:
                pass
                #time.sleep(1)

            syslog.syslog( '=== %s ===' % 'Exit' )
            # отключаем таймер
            signal.setitimer(signal.ITIMER_REAL, 0)
            # удаляю pid-файл
            os.remove(self.pid_file)
        except Exception as e:
            syslog.syslog( '=== %s ===' % str(e) )

    def process_alarm_signal(self):
        try:
            if self.is_exit_alarm == 1 or self.need_break is True:
                return;

            self.is_exit_alarm = 1
            if self.debug:
                print '{} - alarm_checking'.format(datetime.datetime.now())
            
            is_face = self.face.read()
            if is_face is False:
                self.time += self.timer
                if self.time > self.time_out:
                    # гашу дисплей
                    os.system('cinnamon-screensaver-command --lock &')
                    if self.debug:
                        print("OUT %d" % self.time)
                elif self.debug:
                    print("No face %d" % self.time)
            else:
                self.time = 0
                os.system('cinnamon-screensaver-command -d &')
                if self.debug:
                    print('Yes face %d' % self.time)

            self.is_exit_alarm = 0
        except Exception as e:
            self.is_exit_alarm = 0
            syslog.syslog( '=== %s ===' % str(e) )

    def __move_mouse(x,y):
        dll = cdll.LoadLibrary('libX11.so')
        d = dll.XOpenDisplay(None)
        root = dll.XDefaultRootWindow(d)
        dll.XWarpPointer(d,None,root,0,0,0,0,x,y)
        dll.XCloseDisplay(d)

        syslog.syslog( '=== %s ===' % 'set cursor 0 0' )
Ejemplo n.º 50
0
def api_slack():
    text = request.POST.text
    if text == "list":
        characters = config.CHARACTERS.keys()
        res = ', '.join(characters)
        return { "text" : res }

    if not text:
        return ""

    splited = text.split()

    # filter text
    for string in splited:
        if not string in config.CHARACTERS:
            return ""

    # splited -> character list
    characters = list(map(config.CHARACTERS.get, splited))

    grouped_pics = (Face.select(Face.pic_path)
                        .where(Face.character << splited)
                        .group_by(Face.pic_path, Face.character))

    pic = (Face.select(grouped_pics.c.pic_path)
        .from_(grouped_pics)
        .group_by(grouped_pics.c.pic_path)
        .having(fn.Count() > len(characters) - 1)
        .order_by(fn.Random())
        .limit(1))

    faces = list(Face.select().where(Face.pic_path << pic, Face.character << splited))

    if not faces:
        return {
            "username": text,
            "icon_emoji": ":upside_down_face:",
            "text": "not found"
            }

    pic_path = faces[0].pic_path
    original_url = _build_url(pic_path)
    thumb_url = _build_url(faces[0].thumb_path)

    probabilities = " | ".join(map(lambda face: "{0}: {1:.2f}%, {2}: {3:.2f}%".format(
                        face.character,
                        face.probability * 100,
                        face.character_1,
                        face.probability_1 * 100
                        ), faces))

    footer = "Detail: {0}\n{1}".format(_build_detail_url(pic_path), probabilities)

    return {
            "username": text,
            "icon_url": _build_static_url(characters[0]["img_path"]),
            "attachments": [
                {
                    "fallback": original_url,
                    "title": original_url,
                    "title_link": original_url,
                    "image_url": thumb_url,
                    "footer":footer
                    }
                ]
            }
Ejemplo n.º 51
0
def _get_random(character):
    return Face.select().where(Face.character == character).order_by(
            fn.Random()).first()
Ejemplo n.º 52
0
	def addNewFace(self, location):
		fc = Face()
		fc.id = self.totalFaceCount
		self.totalFaceCount += 1
		fc.setPosition(location)
		self.visibleFaceList.append(fc)