일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- 딥러닝
- docker
- ssd
- 머신러닝
- C++
- AWS
- 자료구조 및 실습
- 2단계
- SWEA
- 모두를 위한 딥러닝 강좌 시즌1
- Python
- 백준
- MySQL
- Object detection
- 파이썬
- pytorch
- CS231n
- cs
- 실전알고리즘
- 프로그래머스
- 이것이 코딩테스트다 with 파이썬
- 3단계
- test-helper
- 그리디
- 코드수행
- 1단계
- 구현
- ubuntu
- 전산기초
- STL
- Today
- Total
곰퓨타의 SW 이야기
python openCV로 실시간 영상 분석 뿌시기 본문
스마트 미러를 팀원들과 만들기 위해, openCV를 활용한 얼굴 인식 및 azure에서 제공하는 표정인식 api를 활용하는 방법을 익혀야 했다. 따라서 이번주에 간단하게 익힌 방법을 작성하고, 추가할 부분이 있다면 차근차근 추가하며 공부를 해보고자 한다💪
1. openCV 설치하기
파이썬에서 cv2 라이브러리를 import 하기 위해서 다음과 같은 설치를 해야한다.
pip install opencv-python
2. openCV 오픈소스 다운받기
openCV를 활용하여 여러가지 분류기를 활용할 수 있는 오픈소스가 공개되어 있다!! 이들은 아래 깃허브 사이트에서 다운로드가 가능하다.
opencv/opencv
Open Source Computer Vision Library. Contribute to opencv/opencv development by creating an account on GitHub.
github.com
3. openCV 파일에 있는 'haarcascade_frontalface_default.xml' 활용하여 실시간 영상에서 얼굴 인식
이는 다음과 같은 공식 라이브러리를 참고했다.
docs.opencv.org/master/dd/d43/tutorial_py_video_display.html
OpenCV: Getting Started with Videos
Goal Learn to read video, display video, and save video. Learn to capture video from a camera and display it. You will learn these functions : cv.VideoCapture(), cv.VideoWriter() Capture Video from Camera Often, we have to capture live stream with a camera
docs.opencv.org
cap = cv2.VideoCapture(0)
노트북 컴퓨터를 키고, 얼굴인식 파일을 열었다.
face_cascade = cv2.CascadeClassifier('주소/data/haarcascades/haarcascade_frontalface_default.xml')
얼굴 인식 파일을 읽어온다. 얼굴 인식 파일은 openCV library에서 'haarcascade_frontalface_default.xml' 경로에 저장되어 있다.
faces = face_cascade.detectMultiScale(gray, 1.4, 5)
objects = cv.CascadeClassifier.detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]])
각 파라미터는 다음을 의미한다.
image | Matrix of the type CV_8U containing an image where objects are detected. |
objects | Vector of rectangles where each rectangle contains the detected object, the rectangles may be partially outside the original image. |
scaleFactor | Parameter specifying how much the image size is reduced at each image scale. |
minNeighbors | Parameter specifying how many neighbors each candidate rectangle should have to retain it. |
flags | Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade. |
minSize | Minimum possible object size. Objects smaller than that are ignored. |
maxSize | Maximum possible object size. Objects larger than that are ignored. If maxSize == minSize model is evaluated on single scale |
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
cv에 있는 rectangle 함수를 통해 빨간색의 굵기가 2인 직사각형을 그려낸다.
color 자리의 색상 파라미터는 각 자리가 (파란색, 초록색, 빨간색) 이다.
img = cv.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
cv2.waitKey(1) == ord('q')
waitKey는 'q' key event를 1ms 동안 기다린다.
q라는 이벤트가 들어오면 while문을 break 하여 실시간 영상을 종료하고 메모리를 삭제한다.
최종 코드는 다음과 같다.
#pip install opencv-python
import cv2
#노트북 카메라에서 영상을 읽어온다
cap = cv2.VideoCapture(0)
#얼굴 인식 캐스케이드 파일 읽는다
face_cascade = cv2.CascadeClassifier('주소/data/haarcascades/haarcascade_frontalface_default.xml')
while(True):
# frame 별로 capture 한다
ret, frame = cap.read()
# 좌우 반전은 1, 상하반전은 0
frame = cv2.flip(frame,1)
# 프레임이 제대로 읽어지지 않은 경우
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#detectMultiScale (InputArray image, std::vector< Rect > &objects, double scaleFactor=1.1, int minNeighbors=3, int flags=0, Size minSize=Size(), Size maxSize=Size())
faces = face_cascade.detectMultiScale(gray, 1.4, 5)
# 빨간 사각형으로 인식된 얼굴을 표시한다.
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
#webCamera라는 이름으로 실시간 화면을 보여준다.
cv2.imshow('webCamera',frame)
# q를 누르면 종료되도록 하는 코드이다.
if cv2.waitKey(1) == ord('q'):
break
# 메모리를 해제시켜준다.
cap.release()
cv2.destroyAllWindows()
'Project > 스마트미러' 카테고리의 다른 글
'표정 분석 스마트미러' 개요 및 총 구조 (0) | 2021.04.13 |
---|