yeon_vision_
[가상현실] tracking1 본문
1. 단순 opencv 설치 & video 입력 테스트
https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
Getting Started with Videos — OpenCV 3.0.0-dev documentation
Capture Video from Camera Often, we have to capture live stream with camera. OpenCV provides a very simple interface to this. Let’s capture a video from the camera (I am using the in-built webcam of my laptop), convert it into grayscale video and display
docs.opencv.org
import numpy as np
import cv2
cap = cv2.VideoCapture(0) # 0,1,2.... 카메라의 index. 카메라로부터 비디오를 불러오는 함수.
#cap = cv2.VideoCapture("불러오고 싶은 비디오 file 경로")
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #비디오를 gray scale로 변경
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'): # esc나 q라는 키입력이 들어오기 전까지 실행
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
파이참에서 실행하니까 잘됨.
2. 얼굴 & 눈 인식.
가장 정통적인 Haar Feature-based Cascade Classifiers.
우선 얼굴 인식하고 거기서 더 줄여서 눈코입을 인식한다.
얼굴인식할때는 눈이 좀더 어둡고... 아래 filter등을 opencv에서 이미 학습해뒀다.
x,y,w,h
왼쪽상단의 (x,y)와 높이 너비를 알면 직사각형 위치를 알 수 있다.
import numpy as np
import cv2 as cv
#face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('haarcascade_eye.xml')
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml')
img = cv.imread('family.jpeg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # 해당 (x,y,w,h) 위치에 rectangle그려라.
roi_gray = gray[y:y+h, x:x+w] # gray 에서 얼굴영역만 저장
roi_color = img[y:y+h, x:x+w] # color 에서 얼굴영역만 저장
eyes = eye_cascade.detectMultiScale(roi_gray) # 눈 위치 찾아서
for (ex,ey,ew,eh) in eyes:
cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) #거기에도 rectangle.
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
파이참에서 실행해서 성공.
3. 이제 두 파일을 합쳐서 동영상에 대해 얼굴 인식을 해보자.
import numpy as np
import cv2 as cv
#############################
### 1. video 입력 ###
#############################
cap = cv.VideoCapture(0) # 0,1,2.... 카메라의 index. 카메라로부터 비디오를 불러오는 함수.
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #비디오를 gray scale로 변경
#################################
### 2. 얼굴 인식 시작 ###
#################################
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml')
#img = cv.imread('family.jpeg')
#gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) # 해당 (x,y,w,h) 위치에 rectangle그려라.
roi_gray = gray[y:y + h, x:x + w] # gray 에서 얼굴영역만 저장
roi_color = frame[y:y + h, x:x + w] # color 에서 얼굴영역만 저장
eyes = eye_cascade.detectMultiScale(roi_gray) # 눈 위치 찾아서
for (ex, ey, ew, eh) in eyes:
cv.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) # 거기에도 rectangle.
#cv.imshow('img', image)
#cv.waitKey(0)
#cv.destroyAllWindows()
#################################
### 2. 얼굴 인식 끝 ###
#################################
# Display the resulting frame
cv.imshow('frame', frame)
if cv.waitKey(1) & 0xFF == ord('q'): # esc나 q라는 키입력이 들어오기 전까지 실행
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
4. 사실 이것은 [tracking]이 아니고 [실시간 얼굴 검출]임.
매 frame마다 새로 검출하는 것이라.
5. [보너스] 얼굴에 사진 붙여보자.
# 2071042 임연우
# 가상현실 실시간얼굴검출
import numpy as np
import cv2 as cv
from PIL import Image
#############################
### 1. video 입력 ###
#############################
cap = cv.VideoCapture(0) # 0,1,2.... 카메라의 index. 카메라로부터 비디오를 불러오는 함수.
paste_img = Image.open('heart.png')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #비디오를 gray scale로 변경
#################################
### 2. 얼굴 인식 시작 ###
#################################
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml')
#img = cv.imread('family.jpeg')
#gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) # 해당 (x,y,w,h) 위치에 rectangle그려라.
roi_gray = gray[y:y + h, x:x + w] # gray 에서 얼굴영역만 저장
roi_color = frame[y:y + h, x:x + w] # color 에서 얼굴영역만 저장
eyes = eye_cascade.detectMultiScale(roi_gray) # 눈 위치 찾아서
for (ex, ey, ew, eh) in eyes:
cv.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) # 거기에도 rectangle.
# 눈에 heart 붙여보자.
frame_img = Image.fromarray(frame) #frame(np array)를 PIL Image 형태로 변환
frame_img.paste(paste_img, (ex + ew, ey + eh)) #거기서 paste
frame = np.array(frame_img) #해당 다시 np array 형식으로 변환
#cv.imshow('img', image)
#cv.waitKey(0)
#cv.destroyAllWindows()
#################################
### 2. 얼굴 인식 끝 ###
#################################
# Display the resulting frame
cv.imshow('frame', frame)
if cv.waitKey(1) & 0xFF == ord('q'): # esc나 q라는 키입력이 들어오기 전까지 실행
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
잘 붙어지긴하는데 nparray <-> PIL Image 변환과정에서 color 형식이 깨져서 파란색으로 보인다.
(이거 졸프 할때 해결했었는데 할때마다 기억이 안나네.....)
이유는 openCV는 BGR로 사용하지만,
Matplotlib는 RGB로 이미지를 보여주기 때문.
즉 결과 값은 3차원 배열의 값중 첫번째와 세번째 배열값을 서로 바꿔 주여야함.
'OTHER COURSE WORK > 2023-1 가상현실' 카테고리의 다른 글
[가상현실] tracking 2 (0) | 2023.05.11 |
---|---|
[가상현실] Vuforia Engine (0) | 2023.04.20 |
[가상현실] ML Agent (0) | 2023.04.13 |
[가상현실] Unity NavMesh (0) | 2023.04.09 |
[가상현실] 2D game tutorial (0) | 2023.03.30 |