基於opevcv的面部檢測pip install opencv-python

首先導入opencv包

命令符輸入pip --version看是否安裝有pip(沒有的話去官網下載一個pip並解壓,然後cmd打開命令輸入

python setup.py install  即可安裝pip)

如果確認安裝了,直接輸入

pip install opencv-python

安裝opencv包,完成執行如下代碼即可實現

識別代碼如下:

import cv2
import os.path


def detect(filename, cascade_file = "haarcascade_frontalface_alt.xml"):
    if not os.path.isfile(cascade_file):
        raise RuntimeError("%s: not found" % cascade_file)

    cascade = cv2.CascadeClassifier(cascade_file)
    image = cv2.imread(filename)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    faces = cascade.detectMultiScale(gray,
                                     # detector options
                                     scaleFactor = 1.1,
                                     minNeighbors = 5,
                                     minSize = (24, 24))
    i=0
    for (x, y, w, h) in faces:
        i+=1
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
        temp=image[y:y+h,x:x+w,:]
        cv2.imwrite('%s_%d.jpg'%(os.path.basename(filename).split('.')[0],i),temp)
    cv2.imshow("AnimeFaceDetect", image)
    cv2.waitKey(0)
    cv2.imwrite("out.jpg", image)


detect('20170629143316297.png!wap.jpg')  #自己選擇圖片







效果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章