본문 바로가기
수업(국비지원)/Python

[Python] 2개의 이미지 호출, 이미지에서 얼굴, 눈 표시하기

by byeolsub 2023. 4. 27.

 📌

# bitwise 함수 : 2개의 이미지 호출하기 
import numpy as np, cv2
image1 = np.zeros((300, 300), np.uint8) # 300행, 300열 검은색 영상 생성
image2 = image1.copy()
image1.shape
cv2.imshow("image1", image1)
cv2.imshow("image2", image2)

h, w = image1.shape[:2]
print(h, w)
cx, cy = w//2, h//2
print(cx, cy)
cv2.circle(image1, (cx, cy), 100, 255, -1) # 중심에 원 그리기
cv2.rectangle(image2, (0, 0, cx, h), 255, -1)
image3 = cv2.bitwise_or(image1, image2) # 원소 간 논리합
image4 = cv2.bitwise_and(image1, image2) # 원소 간 논리곱
image5 = cv2.bitwise_xor(image1, image2) # 원소 간 배타적 논리합
image6 = cv2.bitwise_not(image1) # 행렬 반전

cv2.imshow("bitwise_or", image3)
cv2.imshow("bitwise_and", image4)
cv2.imshow("bitwise_xor", image5)
cv2.imshow("bitwise_mot", image6)
cv2.waitKey(0)

 📌

# -*- coding: utf-8 -*-
"""
Created on Thu Dec 29 09:06:57 2022

@author: KITCOOP
2022-12-29.py
"""
import cv2, numpy as np
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml") # 정면 검출기
eye_cascade = cv2.CascadeClassifier("haarcascade_eye.xml") # 눈 검출기
image = cv2.imread('images/face1.jpg', cv2.IMREAD_COLOR)
cv2.imshow("image", image)
image.shape # (349, 500, 3) 
# cvtColor() : 이미지 변환
# cv2.COLOR_BGR2GRAY : 컬러이미지 -> 흑백이미지.
# cv2.COLOR_BGR2HSV : 컬러이미지 -> 색상 중 지배색상으로 변환.
# cv2.COLOR_BGR2RGB : 컬러이미지 -> 색상 반전.
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 명암도 영상 변환
gray = cv2.equalizeHist(gray) # 히스토그램 평활화
# gray : 이미지값
# 1.1 : 영상 축소. 기본값 1.1
# 2 : 최소 이웃되는 사각형 값.
# (100, 100) : 최소 객체의 크기.
faces = face_cascade.detectMultiScale(gray, 1.1, 2, 0, (100, 100)); # 얼굴 검출
if faces.any() : # 얼굴 사각형 검출?
    x, y, w, h = faces[0] # 사각형의 좌표
    # face_image : 얼굴 영역
    face_image = image[y:y + h, x:x + w] # 얼굴 영역 영상 가져오기
    eyes = eye_cascade.detectMultiScale(face_image, 1.15, 7, 0, (25, 20)) # 눈검출 수행
    if len(eyes) == 2 : # 눈 사각형이 검출되면
       for ex, ey, ew, eh in eyes : 
           center = (x + ex + ew // 2, y + ey + eh // 2)
           cv2.circle(image, center, 10, (0, 255, 0), 2) # 눈 중심에 원표시
       else :
           print("눈 미검출")
       cv2.rectangle(image, faces[0], (255, 0, 0), 2) # 얼굴 검출 사각형
       cv2.imshow("image", image)
else : print("얼굴 미검출")
cv2.waitKey(0)