opencv+python 自动绿帽机

具体内容,直接看注释吧,该注释的我都注释掉了。

# coding:utf-8
import cv2
# 待检测的图片路径
imagepath = r'D://greenhat//2.jpg'

# 获取训练好的人脸的参数数据,这里直接从GitHub上使用默认值,需要自己去下载
face_cascade = cv2.CascadeClassifier(r'D://greenhat//haarcascade_frontalface_default.xml')

# 读取图片
image = cv2.imread(imagepath)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

# 填上绿帽子的地址
gh = cv2.imread(r'D://greenhat//gh.png')
# 探测图片中的人脸
faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor = 1.022,#需>1,越小的话,检测越宽泛,调整参数用
    minNeighbors = 5,
    minSize = (20,20),#最小脑袋
)

print("发现{0}个人脸!".format(len(faces)))

for(x,y,w,h) in faces:
    gh2 = cv2.resize(gh, (0,0), fx=0.3, fy=0.3)
    sp = gh2.shape
    for x1 in range(0,sp[0]):
        for y1 in range(0,sp[1]):
            # 去掉白颜色,只留下绿颜色,直接特判RGB
            if gh2[x1,y1,1]-gh2[x1,y1,0] > 60 and gh2[x1,y1,2] - gh2[x1,y1,1] > 7:
                image[y-w+x1+12,x+y1]=gh2[x1,y1]

    #   利用自带的画绿帽子
    #cv2.rectangle(image,(x,y-3),(x+w,y),(0,255,0),thickness=3)
    #cv2.circle(image,(x+int(w/2),y-4),2,(0,255,0),10)

cv2.imshow("Find Faces!",image)
cv2.waitKey(0)
posted @ 2017-06-21 15:38 qscqesze 阅读(...) 评论(...) 编辑 收藏