본문 바로가기

언어/Python

[ Python ] OpenCV 손 검출과 얼굴 모자이크

먼저 아래 명령어를 통해 OpenCV 를 설치해줍니다.

pip install opencv-python

 

전체코드 입니다

import cv2
import numpy as np

cascadeFace = cv2.CascadeClassifier("./haarcascade_frontalface_alt.xml")
cascadeHand = cv2.CascadeClassifier("./haarcascade_hand.xml")


def removeFace(img, cascade):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)
    rects = cascade.detectMultiScale(gray, 1.4, 5)
    return rects

def detectHand(img, cascade):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)
    rects = cascade.detectMultiScale(gray, 1.4, 5)
    return rects

capt = cv2.VideoCapture(0)
delback = cv2.createBackgroundSubtractorMOG2()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))

while capt.isOpened():
    success, frame = capt.read()
    if success:
        # 검출 작업
        ycrcb = cv2.cvtColor(frame,cv2.COLOR_BGR2YCrCb)
        cam1 = cv2.inRange(ycrcb,np.array([0,133,84]),np.array([255,173,127]))
        cam2 = delback.apply(frame)
        cam2 = cv2.morphologyEx(cam2, cv2.MORPH_OPEN, kernel)

        rectFace = removeFace(frame, cascadeFace)
        
        hand = cv2.GaussianBlur(cam2, (3,3), 0)
        k = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
        hand = cv2.morphologyEx(hand, cv2.MORPH_CLOSE, k)
        hand = cv2.erode(hand, k)

        rectHand = detectHand(frame, cascadeHand)


        for x1, y1, x2, y2 in rectFace:
            cv2.rectangle(hand, (x1-100, 0), (x2+1000, 2000), (0,0,0), -1)

        for x1, y1, x2, y2 in rectHand:
            cv2.rectangle(frame, (x1-100, y1-100), (x2-100, y2-100), (0,255,0), 7)
        

        # 프린트
        cv2.imshow('Def 1 : 카메라', frame)
        cv2.imshow('Def 2 : 손 검출', cam1)
        cv2.imshow('Def 3 : 배경 제거', cam2)
        cv2.imshow('Def 4 : First', hand)



        # ESC
        key = cv2.waitKey(1) & 0xFF
        if (key == 27): 
            break
 
 
capt.release()
cv2.destroyAllWindows()

대략 이러한 형태로 출력이 됩니다.