ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 라즈베리파이에서 OpenCV 정리_2
    전공공부/리눅스 2021. 7. 19. 23:00

    안녕하세요. 개알못입니다~

     

    저번에 이어서 opencv 관련 내용입니다.

    좀더 여유가 있을 때 내용르 보충하겠습니다 :)

     


    1. 실시간 데이터 수집

    # 개알못
    
    import cv2
    import os
    
    cam = cv2.VideoCapture(0)
    cam.set(3, 640) # set video width
    cam.set(4, 480) # set video height
    
    face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    face_id = input(" Write your registration number")
    print(" Look at the camera and wait a minute")
    
    count = 0
    
    while(True):
        ret, img = cam.read()
        img = cv2.flip(img, -1)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
        faces = face_detector.detectMultiScale(gray, 1.3, 5)
        
        for (x,y,w,h) in faces:
        
            cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)     
            count += 1
            
            cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
            cv2.imshow('image', img)
            
        k = cv2.waitKey(100) & 0xff # ESC 누르면 종료
        if k == 27:
            break
            
        elif count >= 30: # 원하는 횟수만큼 데이터가 저장 됨.
             break
             
    cam.release()
    cv2.destroyAllWindows()

     

    2. 수집한 데이터를 학습하기

    # 개알못
    
    import cv2
    import numpy as np
    import os
    from PIL import Image
    
    path = 'dataset'
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
    
    def getImagesAndLabels(path):
    
        imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
        faceSamples=[]
        ids = []
        
        for imagePath in imagePaths:
        
            PIL_img = Image.open(imagePath).convert('L')
            img_numpy = np.array(PIL_img,'uint8')
            id = int(os.path.split(imagePath)[-1].split(".")[1])
            faces = detector.detectMultiScale(img_numpy)
            
            for (x,y,w,h) in faces:
            
                faceSamples.append(img_numpy[y:y+h,x:x+w])
                ids.append(id)
                
        return faceSamples,ids
    
    faces,ids = getImagesAndLabels(path)
    recognizer.train(faces, np.array(ids))
    
    recognizer.write('trainer/trainer.yml')

     

    3.  학습한 파일에 일치하는지 인식하기

    # 개알못
    
    import cv2
    import numpy as np
    import os
    
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('trainer/trainer.yml')
    cascadePath = "haarcascade_frontalface_default.xml"
    
    faceCascade = cv2.CascadeClassifier(cascadePath);
    font = cv2.FONT_HERSHEY_SIMPLEX
    
    id = 0
    
    names = ['None', 'changhwan']
    
    cam = cv2.VideoCapture(0)
    cam.set(3, 640) # set video widht
    cam.set(4, 480) # set video height
    
    minW = 0.1*cam.get(3)
    minH = 0.1*cam.get(4)
    
    while True:
        ret, img =cam.read()
        img = cv2.flip(img, -1) # 상하반전
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        
        faces = faceCascade.detectMultiScale( 
            gray,
            scaleFactor = 1.2,
            minNeighbors = 5,
            minSize = (int(minW), int(minH)),
           )
    
        for(x,y,w,h) in faces:
        
            cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
            id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
    
            if (confidence < 100):
                id = names[id]
                confidence = "  {0}%".format(round(100 - confidence))
                
            else:
                id = "unknown"
                confidence = "  {0}%".format(round(100 - confidence))
            
            cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
            cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  
        
        cv2.imshow('camera',img) 
        
        k = cv2.waitKey(10) & 0xff # ESC 누르면 종료
        if k == 27:
            break
            
    cam.release()
    cv2.destroyAllWindows()

    '전공공부 > 리눅스' 카테고리의 다른 글

    [리눅스] 기본 명령어 2  (0) 2021.08.10
    [리눅스] 기본 명령어 1  (0) 2021.08.04
    라즈베리파이에서 OpenCV 정리_1  (0) 2021.07.18

    댓글

Designed by Tistory.