Ejemplo n.º 1
0
 def undistort_image(self, im):
     cm = cv.Load('camera_matrix.xml')
     dc = cv.Load('distortion_coefficients.xml')
     width, height = cv.GetSize(im)
     display = cv.CreateMat(height, width, cv.CV_8UC3)
     cv.Undistort2(im, display, cm, dc)
     return display
Ejemplo n.º 2
0
    def loadHaars(self):
        faceCascade = cv.Load("haarcascades/haarcascade_frontalface_alt.xml")
        eyeCascade = cv.Load(
            "haarcascades/haarcascade_eye_tree_eyeglasses.xml")
        mouthCascade = cv.Load("haarcascades/haarcascade_mcs_mouth.xml")

        return (faceCascade, eyeCascade, mouthCascade)
Ejemplo n.º 3
0
    def findEyes(self):
        """ Detects eyes in a photo and initializes relevant attributes

        Uses opencv libarary methods to detect a face and then detect the
        eyes in that face. If there are exactly two eye regions found it
        populates the region attributes. If not exactly two
        eye regions are found the method returns false.

        Args:
            None

        Return:
            bool - True if there were no issues. False for any error
        """
        
        #imcolor = cv.LoadImage(self.path)
        imcolor = self.facePhoto

        #Path setups
        cwd = os.path.dirname(os.path.abspath(sys.argv[0]))
        cwd += "/opencv/haarcascades/"
        frontalface = cwd + "haarcascade_frontalface_default.xml"
        eye = cwd + "haarcascade_eye.xml"

        faceCascade = cv.Load(frontalface)
        eyeCascade = cv.Load(eye)
        
        haarEyes = cv.Load(eye)
        storage = cv.CreateMemStorage()
        detectedEyes = cv.HaarDetectObjects(imcolor,haarEyes,storage)

        if DEBUG:
            print "detectedEyes = " + str(detectedEyes)

        if len(detectedEyes) == 2:
            if DEBUG:
                # Draw the rectangle 
                cv.Rectangle(imcolor,(detectedEyes[0][0][0], detectedEyes[0][0][1]), 
                    (detectedEyes[0][0][0] + detectedEyes[0][0][2], 
                    detectedEyes[0][0][1] + detectedEyes[0][0][3]),cv.RGB(155,155,200),2)
                cv.Rectangle(imcolor,(detectedEyes[1][0][0], detectedEyes[1][0][1]), 
                    (detectedEyes[1][0][0] + detectedEyes[1][0][2], 
                    detectedEyes[1][0][1] + detectedEyes[1][0][3]),cv.RGB(155,155,200),2)
                cv.ShowImage("Face with eyes",imcolor)
                cv.WaitKey(0)
                cv.DestroyWindow("Face with eyes")
            left = (detectedEyes[0][0][0], detectedEyes[0][0][1], 
                    detectedEyes[0][0][0] + detectedEyes[0][0][2], 
                    detectedEyes[0][0][1] + detectedEyes[0][0][3])
            right = (detectedEyes[1][0][0], detectedEyes[1][0][1], 
                    detectedEyes[1][0][0] + detectedEyes[1][0][2], 
                    detectedEyes[1][0][1] + detectedEyes[1][0][3])
            if DEBUG:
                print "left: " + str(left)
                print "right: " + str(right)
            self.setEyes(left, right)
            return True
        if DEBUG:
            print "Found more or less than 2 eyes, returning false"
        return False
Ejemplo n.º 4
0
Archivo: lrf.py Proyecto: Mnemonic7/lrf
def init_capture_device(device=-1):
    print "init capture device"
    capture = cv.CreateCameraCapture(device)

    # check that capture device is OK
    if not capture:
        print "Error opening capture device"
        sys.exit(1)

    #call specific camera initialization
    camera_init(capture)

    #Get inital image to set parameters
    image = cv.QueryFrame(capture)  #inital image

    CAMERA_WIDTH = cv.GetSize(image)[0]
    #print CAMERA_WIDTH
    CAMERA_HEIGHT = cv.GetSize(image)[1]
    #print CAMERA_HEIGHT

    #load calibration
    intrinsics = cv.Load(INTRINSICS_FILE)
    distortion = cv.Load(DISTORTION_FILE)
    mapx = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_32F, 1)
    mapy = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_32F, 1)
    cv.InitUndistortMap(intrinsics, distortion, mapx, mapy)

    return capture, mapx, mapy
Ejemplo n.º 5
0
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.imgL = ImageTk.PhotoImage(Image.open("small.png"))
        self.imgR = ImageTk.PhotoImage(Image.open("small2.png"))
        self.rawL = self.imgL
        self.rawR = self.imgR
        self.cvImgR = ""
        self.cvImgL = ""
        self.showRaw = True
        self.showEdge = False
        self.showDisp = False

        self.Q = cv.Load("Q.xml")
        self.mx1 = np.asarray(cv.Load("mx1.xml"))
        self.my1 = np.asarray(cv.Load("my1.xml"))
        self.mx2 = np.asarray(cv.Load("mx2.xml"))
        self.my2 = np.asarray(cv.Load("my2.xml"))

        self.stereo = cv2.StereoSGBM()
        self.stereo.SADWindowSize = 9
        self.stereo.numberOfDisparities = 96
        self.stereo.preFilterCap = 63
        self.stereo.minDisparity = -21
        self.stereo.uniquenessRatio = 7
        self.stereo.speckleWindowSize = 0
        self.stereo.speckleRange = 8
        self.stereo.disp12MaxDiff = 1
        self.stereo.fullDP = False

        #holder varriables for the sliders
        self.SADWindowSizeScale = 9
        self.numberOfDisparitiesScale = 96
        self.preFilterCapScale = 63
        self.minDisparityScale = -21
        self.uniquenessRatioScale = 7
        self.speckleWindowSizeScale = 0
        self.speckleRangeScale = 8
        self.disp12MaxDiffScale = 1
        self.fullDP = False

        self.createWidgets()

        self.SADWindowSizeSlider.set(self.stereo.SADWindowSize)
        self.numberOfDisparitiesSlider.set(self.stereo.numberOfDisparities)
        self.preFilterCapSlider.set(self.stereo.preFilterCap)
        self.minDisparitySlider.set(self.stereo.minDisparity)
        self.uniquenessRatioSlider.set(self.stereo.uniquenessRatio)
        self.speckleWindowSizeSlider.set(self.stereo.speckleWindowSize)
        self.speckleRangeSlider.set(self.stereo.speckleRange)
        self.disp12MaxDiffSlider.set(self.stereo.disp12MaxDiff)

        self.bind("<Up>", self.arwU)
        self.bind("<Down>", self.arwD)
        self.bind("<Left>", self.arwL)
        self.bind("<Right>", self.arwR)
        self.bind("<Button-1>", self.mouseCallback)
        self.bind("<Key>", self.keyCallback)
        self.after(500, self.updateCamera)
Ejemplo n.º 6
0
    def callFaceTracker(self, cameraIndex2):
        arguments = (str(cameraIndex2))
        sys.argv = ["FaceTracker.py"] + list(arguments)
        # sys.argv = ["testing mainf"] + list(m_args)

        parser = OptionParser(
            usage="usage: %prog [options] [filename|camera_index]")
        parser.add_option("-c",
                          "--cascade",
                          action="store",
                          dest="cascade",
                          type="str",
                          help="Haar cascade file, default %default",
                          default=HCDIR +
                          "haarcascade_frontalface_alt_tree.xml")

        # parser.add_option("-c", "--cascade", action="store", dest="cascade", type="str", help="Haar cascade file, default %default", default = "../data/haarcascades/haarcascade_frontalface_alt.xml")
        (options, args) = parser.parse_args()

        self.cascade = cv.Load(options.cascade)
        # detect eyes
        self.cascade2 = cv.Load(DATADIR2 + "haarcascade eye.xml")
        # cascade2 = cv.Load(HCDIR + "..\\eyes\\eye.xml")

        # cascade3 = cv.Load(HCDIR + "haarcascade_mcs_mouth.xml")
        self.cascade3 = cv.Load(DATADIR2 + "Mouth.xml")

        if len(args) != 1:
            parser.print_help()
            sys.exit(1)

        # input_name = args[0]
#         if input_name.isdigit():
#             capture = cv.CreateCameraCapture(int(input_name))
#         else:
#             capture = None

# cv.NamedWindow("result", 1)
        frame_copy = self.cam2.read()  # self.cam.read()

        imageArray = frame_copy[1]
        imageFrame = cv.CreateImageHeader(
            (imageArray.shape[1], imageArray.shape[0]), cv.IPL_DEPTH_8U, 3)
        cv.SetData(imageFrame, imageArray.tostring(),
                   imageArray.dtype.itemsize * 3 * imageArray.shape[1])
        # imageArray = np.zeros(())

        self.tracker = FaceTracker.FaceTracker()
        # print frame_copy.shape
        self.tracker.detect_and_draw(imageFrame, self.cascade, self.cascade2,
                                     self.cascade3)
Ejemplo n.º 7
0
def detect_face(img):

    haarFace = cv.Load('./haarcascade_frontalface_default.xml')

    #RGB_img = cv.fromarray(np.array(rgb[:,:,::-1]))
    allFaces = cv.HaarDetectObjects(cv.fromarray(img),
                                    haarFace,
                                    cv.CreateMemStorage(),
                                    scale_factor=1.1,
                                    min_neighbors=3,
                                    flags=0,
                                    min_size=(50, 50))

    # Get confidences
    if (allFaces != []):
        count_no_face = 0
        #print(allFaces)
        face_confid = [c for ((x, y, w, h), c) in allFaces]

        max_ind = np.argmax(face_confid)
        FINAL_FACE = allFaces[max_ind]

        return FINAL_FACE[0]

    else:
        return []
Ejemplo n.º 8
0
def InitCamera(port=0):
    """ Initialisation de la webcam """
    global CAMERA, CASCADE, DEFAULT_DEVICE_WIDTH, DEFAULT_DEVICE_HEIGHT
    try:
        if hasattr(cv, "CreateCameraCapture"):
            CAMERA = cv.CreateCameraCapture(port)
            frame = cv.QueryFrame(CAMERA)
            if frame == None:
                return False
            DEFAULT_DEVICE_WIDTH = frame.width
            DEFAULT_DEVICE_HEIGHT = frame.height
            CASCADE = cv.Load(
                Chemins.GetStaticPath(
                    "Divers/haarcascade_frontalface_alt2.xml"))

        else:
            CAMERA = cv.VideoCapture(port)
            ret, frame = CAMERA.read()
            if not ret:
                return False
            DEFAULT_DEVICE_HEIGHT, DEFAULT_DEVICE_WIDTH = frame.shape[:2]
            CASCADE = cv.CascadeClassifier(
                Chemins.GetStaticPath(
                    "Divers/haarcascade_frontalface_alt2.xml"))

        return True
    except Exception as err:
        print("Connexion camera impossible :", err)
        return False
Ejemplo n.º 9
0
def faceCrop(imagePattern, boxScale=1):

    faceCascade = cv.Load('haarcascade_frontalface_alt.xml')
    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print 'No Images Found'
        return
    global g
    for img in imgList:
        pil_im = Image.open(img)
        cv_im = pil2cvGrey(pil_im)
        faces = DetectFace(cv_im, faceCascade)
        if faces:
            m = 1
            for face in faces:
                croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale)
                size = 88, 106
                croppedImage = croppedImage.resize(size)
                croppedImage.save("face" + str(g) + ".jpg")

                width, height = croppedImage.size
                box = 0, height / 2, width, height

                lower = croppedImage.crop(box)
                lower.save('mouth' + str(g) + '.jpg')

                g = g + 1
                if m == 1:
                    break

        else:
            print 'No faces found:', img
Ejemplo n.º 10
0
    def __init__(self, parent=None):
        QWidget.__init__(self)
        self.setMinimumSize(640, 480)
        self.setMaximumSize(self.minimumSize())

        # register this callbacks to interact with the faces and the camera
        # image before the widget will view the frame
        self.image_callback = None
        self.face_callback = None

        # init view with correct size, depth, channels
        self.frame = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 3)

        self.storage = cv.CreateMemStorage()
        self.capture = cv.CaptureFromCAM(0)
        self.face_cascade = cv.Load(CSC_PATH +
                                    "haarcascade_frontalface_alt.xml")
        self.fd_wait_frames = 1
        self._fd_wait = self.fd_wait_frames

        # get first frame
        self._query_frame()

        # set refresh rate
        self.timer = QTimer(self)
        self.timer.timeout.connect(self._query_frame)
        self.timer.start(75)
Ejemplo n.º 11
0
    def __init__(self):
        os.system('sudo modprobe bcm2835-v4l2')  # Use pi camera as usb device
        self.camera = cv.CreateCameraCapture(0)  # Set up camera
        # Load cascade data
        self.cascade = cv.Load(
            '/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml'
        )

        self.cam_pan = 90  # Initial pan angle
        self.cam_tilt = 90  # Initial tilt angle

        pan(self.cam_pan - 90)  # Pan to initial position
        tilt(self.cam_tilt - 90)  # Tilt to initial position

        self.min_size = (15, 15)  # Minimum window size
        self.image_scale = 5  # Image shrink scale
        # The factor by which the search window is scaled between the
        # subsequent scans
        self.haar_scale = 1.2
        self.min_neighbors = 2  # Minimum number of neighbor rectangles that makes up an object
        self.haar_flags = cv.CV_HAAR_DO_CANNY_PRUNING  # Mode of operation

        if self.camera:
            self.frame_copy = None

        # Camera warm up
        time.sleep(2)
    def __init__(self,
                 host,
                 port,
                 update_frequency,
                 source="webcam",
                 cascade="haarcascade_frontalface_default",
                 verbose=False,
                 rotation=0):
        """Initialize vision system with update frequency, ip adress, and Haar cascade"""
        self.logger = logging.getLogger("Borg.Brain.Vision.HaarFace_rotate")
        super(HaarFace_rotate, self).__init__(host, port)
        self.update_frequency = update_frequency
        self.__ticker = Ticker(frequency=update_frequency)

        cascadedir = os.environ[
            'BORG'] + "/brain/data/haarcascades/" + cascade + ".xml"
        self.verbose = verbose
        self.cascade = cv.Load(cascadedir)
        self.source = [source]
        self.vid_mem_reader = util.vidmemreader.VidMemReader(self.source)
        # set the type of objects that someone can detect
        self.set_known_objects(['face'])
        # get new image and see what's the resolution for the coordonate to angle/speed converter
        self.get_new_image()
        self.logger.info("Using haar cascade: " + cascadedir)

        self.rotationStep = 20  #Degrees
        self.rotatedImages = []
        self.rotationList = []

        self.rotation = rotation

        for i in range(0, 360, self.rotationStep):
            self.rotationList.append(i)
Ejemplo n.º 13
0
def mouthCrop(imagePattern, boxScale=1):
    # Select one of the haarcascade files:
    #   haarcascade_frontalface_alt.xml  <-- Best one?
    #   haarcascade_frontalface_alt2.xml
    #   haarcascade_frontalface_alt_tree.xml
    #   haarcascade_frontalface_default.xml
    #   haarcascade_profileface.xml
    mouthCascade = cv.Load('mouth.xml')
    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print 'No Images Found'
        return
    global h
    for img in imgList:
        pil_im = Image.open(img)
        cv_im = pil2cvGrey(pil_im)
        lips = DetectFace(cv_im, mouthCascade)
        n = 1
        if lips:
            #n=1
            for lip in lips:
                croppedImage = imgCrop(pil_im, lip[0], boxScale=boxScale)
                croppedImage.save("mouth" + str(h) + ".jpg")
                h = h + 1
        if n == 1:
            break

        else:
            print 'No lips found:', img
Ejemplo n.º 14
0
def faceCrop(imagePattern, boxScale=1):

    faceCascade = cv.Load('haarcascade_frontalface_alt.xml')
    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print 'No Images Found'
        return
    global g
    for img in imgList:
        pil_im = Image.open(img)
        cv_im = pil2cvGrey(pil_im)
        faces = DetectFace(cv_im, faceCascade)
        if faces:
            m = 1
            for face in faces:
                croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale)
                croppedImage.save("testdata/face" + str(g) + ".jpg")
                print 1
                mouthcrop = mouthCrop("testdata/face" + str(g) + ".jpg",
                                      boxScale=1)
                print 2
                g = g + 1

                if m == 1:

                    break

        else:
            print 'No faces found:', img
Ejemplo n.º 15
0
def capture():
    """
        Using the intel training set to capture the face in the video.
        Most of them are frameworks in OpenCV.
    """
    j = 0
    g = os.walk("origin")
    for path, d, filelist in g:
        for filename in filelist:
            img = cv.LoadImage(os.path.join(path, filename))
            image_size = cv.GetSize(img)
            greyscale = cv.CreateImage(image_size, 8, 1)
            cv.CvtColor(img, greyscale, cv.CV_BGR2GRAY)
            storage = cv.CreateMemStorage(0)

            cv.EqualizeHist(greyscale, greyscale)
            cascade = cv.Load('haarcascade_frontalface_alt2.xml')

            faces = cv.HaarDetectObjects(greyscale, cascade, storage, 1.2, 2,
                                         cv.CV_HAAR_DO_CANNY_PRUNING, (50, 50))

            for (x, y, w, h), n in faces:
                j += 1
                cv.SetImageROI(img, (x, y, w, h))
                cv.SaveImage("captured/face" + str(j) + ".png", img)
Ejemplo n.º 16
0
def mouthCrop(imagePattern,boxScale=1):
    # Select one of the haarcascade files:
    #   haarcascade_frontalface_alt.xml  <-- Best one?
    #   haarcascade_frontalface_alt2.xml
    #   haarcascade_frontalface_alt_tree.xml
    #   haarcascade_frontalface_default.xml
    #   haarcascade_profileface.xml
    mouthCascade = cv.Load('mouth.xml')
    imgList=glob.glob(imagePattern)
    if len(imgList)<=0:
        print 'No Images Found'
        return
    global h
    for img in imgList:
        pil_im=Image.open(img)
        cv_im=pil2cvGrey(pil_im)
        lips=DetectFace(cv_im,mouthCascade)
        n=1
        if lips:
            #n=1
            for lip in lips:
                croppedImage=imgCrop(pil_im, lip[0],boxScale=boxScale)
                croppedImage.save("/home/hduser/MAIN PROJECT/CODE/main/testdata/word/""mouth"+str(h)+".jpg")
                h=h+1
	    #os.system("""mogrify -resize 73x50^ \ -gravity center -extent 73x50 /home/hduser/MAIN\ PROJECT/CODE/main/testdata/word/* """)
	    os.system("""mogrify -resize 3000@ /home/hduser/MAIN\ PROJECT/CODE/main/testdata/word/* """)
        if n==1:
	    break
             
                
                
        else:
            print 'No lips found:', img
Ejemplo n.º 17
0
def faceCrop(imagePattern, boxScale=1):
    # Select one of the haarcascade files:
    #   haarcascade_frontalface_alt.xml  <-- Best one?
    #   haarcascade_frontalface_alt2.xml
    #   haarcascade_frontalface_alt_tree.xml
    #   haarcascade_frontalface_default.xml
    #   haarcascade_profileface.xml
    faceCascade = cv.Load('haarcascade_frontalface_alt.xml')
    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print 'No Images Found'
        return
    global g
    for img in imgList:
        pil_im = Image.open(img)
        cv_im = pil2cvGrey(pil_im)
        faces = DetectFace(cv_im, faceCascade)
        if faces:
            m = 1
            for face in faces:
                croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale)
                croppedImage.save("face" + str(g) + ".jpg")

                mouthcrop = mouthCrop("face" + str(g) + ".jpg", boxScale=1)

                g = g + 1
                if m == 1:
                    break

        else:
            print 'No faces found:', img
Ejemplo n.º 18
0
def mouthCrop(imagePattern, boxScale=1):

    mouthCascade = cv.Load('mouth.xml')
    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print 'No Images Found'
        return
    global h
    for img in imgList:
        pil_im = Image.open(img)
        cv_im = pil2cvGrey(pil_im)
        lips = DetectFace(cv_im, mouthCascade)
        n = 1
        size = 88, 53
        if lips:

            for lip in lips:
                croppedImage = imgCrop(pil_im, lip[0], boxScale=boxScale)
                croppedImage = croppedImage.resize(size)
                croppedImage.save("testdata/word/" "mouth" + str(h) + ".jpg")
                h = h + 1

                if (n == 1):
                    break

        else:
            print 'No lips found:', img
Ejemplo n.º 19
0
def compute_spatial_features_from_xml(extract_path, projected_path, vocab_path,
                                      num_levels):
    """ A convenience function that computes spatial pyramid features directly 
    from the XML outputs of vision binaries.

    ${EXTRACT_PATH}.desc and ${PROJECTED_PATH}.desc must exist.

    Args:
        extract_path: Path to output of `dense_feature_extract`.
        projected_path: Path to output of `pca_projection`.
        vocab_path: Path to output of `vocab_kms`.
        num_levels: Number of levels.

    Returns:
        Ndarray with shape [NUM_IMAGES, NUM_FEATURES].
    """
    dims = extract_from_xml(vocab_path, ['numCenters', 'dimension'])
    vocab = binary_to_ndarray('%s.desc' % vocab_path, dims, np.float32)
    dims = extract_from_xml(projected_path, ['nDescriptors', 'cols'])
    proj = binary_to_ndarray('%s.desc' % projected_path, dims, np.float32)
    keypoints = np.asarray(cv.Load(extract_path, name='keypoints')).squeeze()
    im_height, im_width, num_images = extract_from_xml(
        extract_path, ['image_height', 'image_width', 'nImg'])
    vocab_feat = compute_vocab_features(vocab,
                                        proj).reshape(num_images,
                                                      keypoints.shape[0])
    return compute_spatial_features(vocab_feat, keypoints, vocab.shape[0],
                                    num_levels, im_width, im_height)
Ejemplo n.º 20
0
def faceCrop(imagePattern, boxScale=1):
    # Select one of the haarcascade files:
    #   haarcascade_frontalface_alt.xml  <-- Best one?
    #   haarcascade_frontalface_alt2.xml
    #   haarcascade_frontalface_alt_tree.xml
    #   haarcascade_frontalface_default.xml
    #   haarcascade_profileface.xml
    faceCascade = cv.Load('Mouth.xml')

    imgList = glob.glob(imagePattern)
    if len(imgList) <= 0:
        print 'No Images Found'
        return

    for img in imgList:
        pil_im = Image.open(img)
        cv_im = pil2cvGrey(pil_im)
        faces = DetectFace(cv_im, faceCascade)
        if faces:
            n = 1
            for face in faces:
                croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale)
                if n == 1:
                    croppedImage.save("mouth.jpg")
                fname, ext = os.path.splitext(img)
                croppedImage.save(fname + '_crop' + str(n) + ext)
                n += 1

        else:
            print 'No faces found:', img
Ejemplo n.º 21
0
def detect_face(RGB_img):
    # Image Properties
    #print('Image Size: ({},{})'.format(cv.GetCaptureProperty(CAM_CAPT, cv.CV_CAP_PROP_FRAME_HEIGHT), cv.GetCaptureProperty(CAM_CAPT, cv.CV_CAP_PROP_FRAME_WIDTH)))
    #print('FPS: {}'.format(cv.GetCaptureProperty(CAM_CAPT, cv.CV_CAP_PROP_FPS)))

    RGB_img_mat = cv.fromarray(RGB_img)

    haarFace = cv.Load('haarcascade_frontalface_default.xml')

    #RGB_img = cv.fromarray(np.array(rgb[:,:,::-1]))
    allFaces = cv.HaarDetectObjects(RGB_img_mat,
                                    haarFace,
                                    cv.CreateMemStorage(),
                                    scale_factor=1.1,
                                    min_neighbors=10,
                                    flags=0,
                                    min_size=(50, 50))

    # Get confidences
    if (allFaces != []):

        #print(allFaces)
        face_confid = [c for ((x, y, w, h), c) in allFaces]
        area = [w * h for ((x, y, w, h), c) in allFaces]

        #max_ind = np.argmax(face_confid)
        max_ind = np.argmax(area)
        FINAL_FACE = allFaces[max_ind]

        x0 = FINAL_FACE[0][0]
        y0 = FINAL_FACE[0][1]
        w = FINAL_FACE[0][2]
        h = FINAL_FACE[0][3]

        # Show detected face
        print('Face Detected!!')
        #cv.Rectangle(RGB_img_mat, (x0, y0), (x0+w, y0+h), cv.RGB(0,0,255), 2)

        # Detect eyes only in given face region
        print('Face: ' + str(FINAL_FACE))
        cropped_img = RGB_img[y0:y0 + h, x0:x0 + w]

        #cv.Smooth(cropped_img, cropped_img, cv.CV_GAUSSIAN, 15, 15)
        #print(cv.GetSize(cropped_img))
        #cv.ShowImage('crop', cropped_img)
        #cv.SaveImage('IMAGE.png', cropped_img)
        #allEyes = detect_eyes(cropped_img)

        #print('Eyes: '+str(allEyes))
        #for eye in allEyes:
        #   eye = eye[0]
        #	eye=(eye[0]+x0, eye[1]+y0, eye[2], eye[3])
        #	cv.Rectangle(RGB_img, (eye[0], eye[1]), (eye[0]+eye[2], eye[1]+eye[3]), cv.RGB(255,0,0), 2)

        return np.asarray(cropped_img[:, :])

    else:
        print('No Face!!')
        return RGB_img
Ejemplo n.º 22
0
def track(img, threshold=100):
    '''Accepts BGR image and optional object threshold between 0 and 255 (default = 100).
       Returns: (x,y) coordinates of centroid if found
                (-1,-1) if no centroid was found
                None if user hit ESC
    '''
    cascade = cv.Load("haarcascade_frontalface_default.xml")
    gray = cv.CreateImage((img.width, img.height), 8, 1)
    small_img = cv.CreateImage((cv.Round(
        img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1)

    # convert color input image to grayscale
    cv.CvtColor(img, gray, cv.CV_BGR2GRAY)

    # scale input image for faster processing
    cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)

    cv.EqualizeHist(small_img, small_img)

    center = (-1, -1)
    faces = []
    original_size_faces = []
    #import ipdb; ipdb.set_trace()
    if (cascade):
        t = cv.GetTickCount()
        # HaarDetectObjects takes 0.02s
        faces = cv.HaarDetectObjects(small_img, cascade,
                                     cv.CreateMemStorage(0), haar_scale,
                                     min_neighbors, haar_flags, min_size)
        t = cv.GetTickCount() - t
        if faces:
            for ((x, y, w, h), n) in faces:
                # the input to cv.HaarDetectObjects was resized, so scale the
                # bounding box of each face and convert it to two CvPoints
                pt1 = (int(x * image_scale), int(y * image_scale))
                pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
                # cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0)
                #cv.Rectangle(img, (x,y), (x+w,y+h), 255)
                # get the xy corner co-ords, calc the center location
                x1 = pt1[0]
                x2 = pt2[0]
                y1 = pt1[1]
                y2 = pt2[1]
                centerx = x1 + ((x2 - x1) / 2)
                centery = y1 + ((y2 - y1) / 2)
                center = (centerx, centery)

                scaled = ((x1, y1, x2 - x1, y2 - y1), n)
                original_size_faces.append(scaled)
                # print scaled


#    cv.NamedWindow(WINDOW_NAME, 1)
#    cv.ShowImage(WINDOW_NAME, img)

#    if cv.WaitKey(5) == 27:
#        center = None
    return (center, original_size_faces)
Ejemplo n.º 23
0
def svm_model(in_file_hist_agg, svm_type, svm_kernel, out_file):
    hist = np.asarray(cv.Load(in_file_hist_agg))
    # The first col is the labels for the feature points
    # The last two cols are (vieo_id, timestamps)
    labels = hist[:, 0]
    features = hist[:, 1:-2]
    clf = LibsvmClassifier(svm_type=int(svm_type), kernel_type=int(svm_kernel))
    clf.train(features, labels)
    clf.save_to_file(out_file)
Ejemplo n.º 24
0
 def __init__(self):
     self.MotionDetector = None
     self.capture = None
     self.matcher = SurfMatcher()
     parser = OptionParser(usage="usage: %prog [options] [filename|camera_index]")
     parser.add_option("-c", "--cascade", action="store", dest="cascade", type="str", help="Haar cascade file, default %default", default=HCDIR + "haarcascade_frontalface_alt_tree.xml")
       
     # parser.add_option("-c", "--cascade", action="store", dest="cascade", type="str", help="Haar cascade file, default %default", default = "../data/haarcascades/haarcascade_frontalface_alt.xml")
     (options, args) = parser.parse_args()
   
     self.cascade = cv.Load(options.cascade)
      # detect eyes
     self.cascade2 = cv.Load(DATADIR2 + "haarcascade eye.xml")
     # cascade2 = cv.Load(HCDIR + "..\\eyes\\eye.xml")
      
     # cascade3 = cv.Load(HCDIR + "haarcascade_mcs_mouth.xml")
     self.cascade3 = cv.Load(DATADIR2 + "Mouth.xml")
     
     self.cascade4 = cv.Load(HCDIR + "haarcascade_mcs_nose.xml")
Ejemplo n.º 25
0
 def __init__(self, xmlpath):
     parser = OptionParser(usage="")
     parser.add_option("-c",
                       "--cascade",
                       action="store",
                       dest="cascade",
                       type="str",
                       help="Haar cascade file, default %default",
                       default=xmlpath)
     (options, args) = parser.parse_args()
     self.cascade = cv.Load(options.cascade)
Ejemplo n.º 26
0
def findface(image):
    #人脸识别,获取脸在图片中的坐标
    grayscale = cv.CreateImage((image.width, image.height), 8, 1)
    cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
    cascade = cv.Load(OPCV_PATH+"/data/haarcascades/haarcascade_frontalface_alt_tree.xml")
    rect = cv.HaarDetectObjects(grayscale, cascade, cv.CreateMemStorage(), 1.015, 2,cv.CV_HAAR_DO_CANNY_PRUNING, (10,10))

    result = []
    for r in rect:
        result.append([(r[0][0], r[0][1]), (r[0][0]+r[0][2], r[0][1]+r[0][3])])

    return result
Ejemplo n.º 27
0
def getMouth2(imcolor,detectedFace,storage=None,DEBUG=None):
    if not storage:
        storage = cv.CreateMemStorage()
    # loading the classifiers
    haarMouth = cv.Load(defaults.haar_mouth)    
    # running the classifiers
    detectedMouth = cv.HaarDetectObjects(imcolor, haarMouth, storage)
    
    # draw a green rectangle where the face is detected
    if DEBUG and detectedMouth:
        for mouth in detectedMouth:
            showRectangle(imcolor,eye,cv.RGB(155, 10, 110))

    return detectedMouth
Ejemplo n.º 28
0
def live_test():
	subdir = 'data/'
	img_kinds = ["happy", "anger", "neutral", "surprise"]
	models = {}
	# load all the models
	print "Loading Models"
	for img_kind in img_kinds:
		print 'loading for: ' + img_kind
		models[img_kind] = svmutil.svm_load_model(subdir + img_kind + '.model')
	print "---------------------"

	print "Loading cascade"
	face_cascade = "haarcascades/haarcascade_frontalface_alt.xml"
	hc = cv.Load(face_cascade)
	print "---------------------"

	capture = cv.CaptureFromCAM(0)
	while True:
		img = cv.QueryFrame(capture)
		cv.ShowImage("camera",img)
		key_pressed = cv.WaitKey(50)
		if key_pressed == 27:
			break
		elif key_pressed == 32:
			print '~> KEY PRESSED <~'
			# do face detection
			print 'detecting face'
			returned = face.handel_camera_image(img, hc)
			if returned == None:
				print "No face || more than one face"
				pass
			else:
				(img_o, img_face) = returned
				cv.ShowImage("face",img_face)
				# get features from the face
				results = {}
				for img_kind in img_kinds:
					test_data = get_image_features(img_face, True, img_kind)
					predict_input_data = []
					predict_input_data.append(test_data)

					# do svm query
					(val, val_2, label) = svmutil.svm_predict([1] ,predict_input_data, models[img_kind])
					results[img_kind] = label[0][0]
					print img_kind + str(results[img_kind])

				sorted_results = sorted(results.iteritems(), key=operator.itemgetter(1))
				print sorted_results[len(sorted_results)-1][0]

				print "---------------------"
Ejemplo n.º 29
0
def getIntrinsics(filepath):
    """
    Given a file path to camera intrinsics, parse
    out the parameters.

    @param filepath Path to read
    @return fx, fy, cx, cy
    """
    camera = np.array(cv.Load(filepath, cv.CreateMemStorage(), "cameraMatrix"))
    fx = camera[0][0]
    fy = camera[1][1]
    cx = camera[0][2]
    cy = camera[1][2]
    return fx, fy, cx, cy
def InitCamera(port=0):
    """ Initialisation de la webcam """
    global CAMERA, CASCADE, DEFAULT_DEVICE_WIDTH, DEFAULT_DEVICE_HEIGHT
    try :
        CAMERA = cv.CreateCameraCapture(port)
        frame = cv.QueryFrame(CAMERA)
        if frame == None :
            return False
        DEFAULT_DEVICE_WIDTH = frame.width
        DEFAULT_DEVICE_HEIGHT = frame.height
        CASCADE = cv.Load(Chemins.GetStaticPath("Divers/haarcascade_frontalface_alt2.xml"))
        return True
    except Exception, err :
        print err
        return False