当前位置: 首页>>代码示例>>Python>>正文


Python cv2.CascadeClassifier方法代码示例

本文整理汇总了Python中cv2.CascadeClassifier方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.CascadeClassifier方法的具体用法?Python cv2.CascadeClassifier怎么用?Python cv2.CascadeClassifier使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cv2的用法示例。


在下文中一共展示了cv2.CascadeClassifier方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: detect_face

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def detect_face(img_path, cc_path='../files/haarcascade_frontalface_default.xml'):
    """
    Detect the face from the image, return colored face
    """

    cc = cv2.CascadeClassifier(os.path.abspath(cc_path))
    img_path = os.path.abspath(img_path)
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = cc.detectMultiScale(gray, 1.3, 5)
    roi_color = None

    if len(faces) == 0:
        logging.exception(img_path + ': No face found')
    else:
        x,y,w,h = faces[0]
        _h, _w = compute_size(h, w)
        roi_color = img[y - _h:y + h + _h, x - _w:x + w + _w]

    return roi_color 
开发者ID:lehgtrung,项目名称:face-search,代码行数:23,代码来源:face_detect.py

示例2: main

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def main(url, quality='best', fps=30.0):
    face_cascade = cv2.CascadeClassifier(os.path.join(cv2.haarcascades, 'haarcascade_frontalface_default.xml'))

    stream_url = stream_to_url(url, quality)
    log.info("Loading stream {0}".format(stream_url))
    cap = cv2.VideoCapture(stream_url)

    frame_time = int((1.0 / fps) * 1000.0)

    while True:
        try:
            ret, frame = cap.read()
            if ret:
                frame_f = detect_faces(face_cascade, frame, scale_factor=1.2)
                cv2.imshow('frame', frame_f)
                if cv2.waitKey(frame_time) & 0xFF == ord('q'):
                    break
            else:
                break
        except KeyboardInterrupt:
            break

    cv2.destroyAllWindows()
    cap.release() 
开发者ID:streamlink,项目名称:streamlink,代码行数:26,代码来源:opencv-face.py

示例3: discern

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def discern(img):
    grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # OpenCV人脸识别分类器
    classifier = cv2.CascadeClassifier(
        "C:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"
    )
    color = (0, 255, 0)  # 定义绘制颜色
    # 调用识别人脸
    faceRects = classifier.detectMultiScale(
        grayImg, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
    if len(faceRects):  # 大于0则检测到人脸
        for faceRect in faceRects:  # 单独框出每一张人脸
            x, y, w, h = faceRect
            # 框出人脸
            cv2.rectangle(img, (x, y), (x + h, y + w), color, 2)

    cv2.imshow("image", img)  # 显示图像 
开发者ID:vipstone,项目名称:faceai,代码行数:19,代码来源:videoOpencv.py

示例4: __init__

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def __init__(self, expiration=5, nbs=5, scale=1.1, inset=150, min_size=10, model_file=face_mdl):
        self.count = 0
        self.eps = 1e-6
        self.activity = []
        self.expiration = expiration
        self.id = utils.id_gen()
        self.q = deque(maxlen=10)
        self.cubit_q = deque(maxlen=50)
        self.skeleton_color = tuple([random.randint(0, 255) for _ in range(3)]) #skeleton_color

        self.faces = []
        self.detector = cv2.CascadeClassifier(model_file)
        self.nbs = nbs
        self.scale = scale
        self.inset = inset
        self.min_size = (min_size, min_size)

        return 
开发者ID:smellslikeml,项目名称:ActionAI,代码行数:20,代码来源:person.py

示例5: detectFaces

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def detectFaces(image_name):
    starttime=time.time()
    img = cv2.imread(image_name)
    face_cascade = cv2.CascadeClassifier(root+"model/haarcascade_frontalface_default.xml")
    if img.ndim == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        gray = img #if语句:如果img维度为3,说明不是灰度图,先转化为灰度图gray,如果不为3,也就是2,原图就是灰度图

    faces = face_cascade.detectMultiScale(gray, 1.2, 5)#1.3和5是特征的最小、最大检测窗口,它改变检测结果也会改变
    result = "["

    for (x,y,width,height) in faces:
        result+=  '{ "x":'+ str(x) +' ,"y":'+ str(y) +' ,"height":'+ str(height)+',"width":'+ str(width)+' } ' +','

    endtime=time.time()

    result=result[:-1]+']'

    return '{"status":true, "data":'+ result +' ,"msg":"成功","runtime":'+ str(endtime-starttime)+'}'

#api返回函数 
开发者ID:Jinnrry,项目名称:FaceRecognition-RestApi,代码行数:24,代码来源:faceApi.py

示例6: __init__

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def __init__(self, cascade_file = './resources/haarcascade_frontalface_default.xml', 
                 min_size = (10, 10),
                 min_neighbors = 20,
                 scale_factor = 1.04,
                 angles = [0],
                 thr = 0.4, 
                 cascade_type = 'haar'):
        '''
        cascade_type - is a string defining the type of cascade
        '''
        print expand_path('.')
        self.cascade_file = cascade_file.rsplit('/',1)[1]
        self._cascade_classifier = cv2.CascadeClassifier(cascade_file)
        self.scale_factor = scale_factor
        self.min_neighbors = min_neighbors
        self.min_size = min_size
        self.cascade_type = cascade_type
        self.angles = angles
        self.thr = thr 
开发者ID:eranid,项目名称:adience_align,代码行数:21,代码来源:cascade_detector.py

示例7: face_recognize

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def face_recognize(self):
        src = self.cv_read_img(self.src_file)
        if src is None:
            return

        gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
        face_cascade = cv.CascadeClassifier('haarcascade_frontalface_alt2.xml')
        faces = face_cascade.detectMultiScale(
            gray,
            scaleFactor=1.15,
            minNeighbors=3,
            minSize=(5, 5)
        )

        for (x, y, w, h) in faces:
            cv.rectangle(src, (x, y), (x + w, y + h), (0, 255, 0), 2)
        self.decode_and_show_dst(src) 
开发者ID:itisyang,项目名称:ImageMiniLab,代码行数:19,代码来源:ImageMiniLab.py

示例8: trainimg

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def trainimg():
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    global detector
    detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    try:
        global faces,Id
        faces, Id = getImagesAndLabels("TrainingImage")
    except Exception as e:
        l='please make "TrainingImage" folder & put Images'
        Notification.configure(text=l, bg="SpringGreen3", width=50, font=('times', 18, 'bold'))
        Notification.place(x=350, y=400)

    recognizer.train(faces, np.array(Id))
    try:
        recognizer.save("TrainingImageLabel\Trainner.yml")
    except Exception as e:
        q='Please make "TrainingImageLabel" folder'
        Notification.configure(text=q, bg="SpringGreen3", width=50, font=('times', 18, 'bold'))
        Notification.place(x=350, y=400)

    res = "Model Trained"  # +",".join(str(f) for f in Id)
    Notification.configure(text=res, bg="SpringGreen3", width=50, font=('times', 18, 'bold'))
    Notification.place(x=250, y=400) 
开发者ID:Spidy20,项目名称:Attendace_management_system,代码行数:25,代码来源:AMS_Run.py

示例9: getFaceCoordinates

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def getFaceCoordinates(image):
    cascade = cv2.CascadeClassifier(CASCADE_PATH)
    
    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.equalizeHist(img_gray)
    rects = cascade.detectMultiScale(
        img_gray,
        scaleFactor=1.1,
        minNeighbors=3,
        minSize=(48, 48)
        )

    # For now, we only deal with the case that we detect one face.
    if(len(rects) != 1) :
        return None
    
    face = rects[0]
    bounding_box = [face[0], face[1], face[0] + face[2], face[1] + face[3]]

    # return map((lambda x: x), bounding_box)
    return bounding_box 
开发者ID:a514514772,项目名称:Real-Time-Facial-Expression-Recognition-with-DeepLearning,代码行数:23,代码来源:face_detection_utilities.py

示例10: detect

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def detect(img_file, detector_xml_path, dest_img_file):
    img = cv2.imread(img_file)
    
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    detector = cv2.CascadeClassifier(detector_xml_path)
    
    min_size = (min(50, gray_img.shape[0] // 10), min(50, gray_img.shape[1] // 10))
    hits = detector.detectMultiScale(gray_img, 1.1, 4, 0, min_size)
    #cv2.groupRectangles(hits, 2)
    print(hits)
    
    hits_img = np.copy(img)
    for (x,y,w,h) in hits:
        cv2.rectangle(hits_img, (x,y), (x+w, y+h), (0,0,255), 2)
    cv2.imwrite(dest_img_file, hits_img) 
开发者ID:pathbreak,项目名称:deepvisualminer,代码行数:18,代码来源:facerec_train.py

示例11: recognize

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def recognize(self, image_path, identity):
        face_recognizer = cv2.face.LBPHFaceRecognizer_create()
        try:
            face_recognizer.read(self.face_recognizer_file)
        except:
            messagebox.showerror('Error', "The class has no data to recongnize from\nor has not been trained yet")
            return "No Training Data"
        test_img = cv2.imread(image_path)
        test_img_gray = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY)
        clf = cv2.CascadeClassifier(self.xml_file)
        all_detected = self.detect_faces(clf, test_img, 1.2)

        students_in_pic = set()
        for (x, y, w, h) in all_detected:
            label, conf = face_recognizer.predict(test_img_gray[y:y + w, x:x + h])
            # print(conf)
            cv2.waitKey(0)
            label_text = identity[label]
            students_in_pic.add(identity[label])
            cv2.rectangle(test_img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(test_img, label_text, (x, y - 5), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 255, 0), 2)
        cv2.imshow("Students in this picture", test_img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        return list(students_in_pic) 
开发者ID:Marauders-9998,项目名称:Attendance-Management-using-Face-Recognition,代码行数:27,代码来源:face_detect.py

示例12: main

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def main():
    #IMG PATHS
    imagePath = "test3.jpg"
    cascPath = "cascades/haarcascade_pedestrian.xml"

    pplCascade = cv2.CascadeClassifier(cascPath)
    image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    gray = normalize_grayimage(gray)
     
    pedestrians = pplCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=10,
        minSize=(32,96),
        flags = cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    print "Found {0} ppl!".format(len(pedestrians))

    #Draw a rectangle around the detected objects
    for (x, y, w, h) in pedestrians:
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imwrite("saida.jpg", image)
    cv2.imshow("Ppl found", image)
    cv2.waitKey(0)
    
    return 0 
开发者ID:felipecorrea,项目名称:pedestrian-haar-based-detector,代码行数:32,代码来源:detect.py

示例13: getPeakFaceFeatures

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def getPeakFaceFeatures():
    net = DecafNet()
    cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')

    features = numpy.zeros((number_sequences,feature_length))
    labels = numpy.zeros((number_sequences,1))
    counter = 0
    # Maybe sort them
    for participant in os.listdir(os.path.join(data_dir,image_dir)):
        for sequence in os.listdir(os.path.join(data_dir,image_dir, participant)):
            if sequence != ".DS_Store":
                image_files = sorted(os.listdir(os.path.join(data_dir,image_dir, participant,sequence)))
                image_file = image_files[-1]
                print counter, image_file
                imarray = cv2.imread(os.path.join(data_dir,image_dir, participant,sequence,image_file))
                imarray = cv2.cvtColor(imarray,cv2.COLOR_BGR2GRAY)
                rects = cascade.detectMultiScale(imarray, 1.3, 3, cv2.cv.CV_HAAR_SCALE_IMAGE, (150,150))
                if len(rects) > 0:
                    facerect=rects[0]
                    imarray = imarray[facerect[1]:facerect[1]+facerect[3], facerect[0]:facerect[0]+facerect[2]]
                scores = net.classify(imarray, center_only=True)
                features[counter] = net.feature(feature_level).flatten()
                label_file = open(os.path.join(data_dir,label_dir, participant,sequence,image_file[:-4]+"_emotion.txt"))
                labels[counter] = eval(label_file.read())
                label_file.close()
                counter += 1

    numpy.save("featuresPeakFace5",features)
    numpy.save("labelsPeakFace5",labels) 
开发者ID:Zebreu,项目名称:ConvolutionalEmotion,代码行数:31,代码来源:emotionclassification.py

示例14: detectFaces

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def detectFaces(frame):
    cascPath = "../data/haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(cascPath)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    detected_faces = faceCascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=6,
            minSize=(50, 50),
            flags=cv2.CASCADE_SCALE_IMAGE)
    return gray, detected_faces 
开发者ID:its-izhar,项目名称:Emotion-Recognition-Using-SVMs,代码行数:13,代码来源:Train Classifier and Test Video Feed.py

示例15: __init__

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CascadeClassifier [as 别名]
def __init__(self):
        # self.model = cv2.CascadeClassifier(
        #         "models/cascade/fullbody_recognition_model.xml")
        # self.model = cv2.CascadeClassifier(
        #         "models/cascade/upperbody_recognition_model.xml")
        self.model = cv2.CascadeClassifier(
                "models/cascade/facial_recognition_model.xml")
        self.colors = np.random.uniform(0, 255, size=(100, 3)) 
开发者ID:cristianpb,项目名称:object-detection,代码行数:10,代码来源:cascade.py


注:本文中的cv2.CascadeClassifier方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。