Python 2.7&OpenCV 3.0 얼굴 검 사 를 위 한 간단 한 인 스 턴 스

       Anaconda(      Python    ,  IPython、Spyder     ,   numpy、matplotlib      ) OpenCV3.0。
   Anaconda   IDE(Spyder)  ,       ,               。      cv2.CascadeClassifier()       xml    。    :
def detectFaces(imagePath):
    img = cv2.imread(imagePath)
    #  openCV                haarcascade_frontalface_default.xml
    faceCascade = cv2.CascadeClassifier(r"D:\Software\OpenCV3.0\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml")
    #    Nonetype object has no attribute ndim  imread()      
    #if  :  img   3,       ,       gray,    3,   2,       
    if img.ndim == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        gray = img 

    faces = faceCascade.detectMultiScale(gray, 1.2, 6)#1.2 6      、      ,           
    result = []
    for (x,y,width,height) in faces:
        result.append((x,y,x+width,y+height))
    return result
       ,                       。    :
def savePictures(imagePath):
    faces = detectFaces(imagePath)
    if faces:
        #      save_dir   。
        #Image  :Image.open      ,crop    (       detectFaces     ),save  。
        saveFolder = imagePath.split('.')[0]+"_faces"
        os.mkdir(saveFolder)
        count = 0
        for (x1,y1,x2,y2) in faces:
            fileName = os.path.join(saveFolder,str(count)+".jpg")
            Image.open(imagePath).crop((x1,y1,x2,y2)).save(fileName)
            count+=1
  ,                    ,    :
"""
        ,       。
  Image   draw  ,Image.open      ,ImageDraw.Draw      draw  ,     draw   rectangle     (      detectFaces     ),outline       (B,G,R)。
 :          ,   outline,       RGB  。
"""
def drawPictures(imagePath):
    faces = detectFaces(imagePath)
    if faces:
        img = Image.open(imagePath)
        drawInstance = ImageDraw.Draw(img)
        for (x1,y1,x2,y2) in faces:
            drawInstance.rectangle((x1,y1,x2,y2), outline=(255, 0,0))
        img.save(imagePath.split('.')[0]+"_faces"+".jpg")

좋은 웹페이지 즐겨찾기