본문 바로가기
비트캠프(AI아카데미)/TIL&WIL

[비트캠프 - 클라우드 기반 AlaaS 개발자 과정] 22.11.03.(DAY-14) TIL

by 그냥_살자 2022. 11. 4.

1. 이론

1) 코드 내 이론

<로컬 이미지 불러오기>

img = cv.imread(파일경로)
cv.imshow(??, img)
cv.waitKey(0)
cv.destroyAllWindows()

<크롤링(url) 이미지 불러오기>

HEADERS = 'User-Agent': 'My User Agent 1.0' # 출처:구글
res = requests.get(params[1], headers=HEADERS) # 자료불러오기
img = Image.open(BytesIO(res.content) # 
img = np.array(img)) #
plt.imshow(Image.fromarray(gray)) #
plt.show() #

2) 그 외 이론

Haar Cascade는 머신 러닝기반의 오브젝트 검출 알고리즘 ⇒ 얼굴인식 써먹음

** object dectection(오브젝트 검출) ⇒ 사람얼굴 여러 개 있어도 갖고 있는 것만 오브젝트. 그 외엔 다 노이즈

가중치

⇒ 그레이스케일 후 진한 정도를 미분해서 숫자로 바꿔 컴퓨터가 이식 및 처리

얼굴에서 눈동자를 젤 많이 인식

Cascade Classifier(폭포 분류기?)

Cascade Classifier ⇒ 채질(윈도우)

윈도우로 하르 특징을 적용해서 얼굴을 검출(6000개 특징..) → 비효율

엣지 - 캐니, 직선 - 허프, 얼굴 - 하르

딥러닝 필터와 커널과 윈도우

cognition vs extriction

 

3) 놓침

케니알고리즘??

⇒ 선으로 사람형상 그림

허프알고리즘??

S = C (2형식) 논리구조?

엣지 검출 원리 : 사진을 미분해서 그걸 숫자로 인식 → 분석

회사단골질문 ⇒ 하르 알고리즘??

하르 픽쳐 셀렉션?

픽셀 = 아톰?

극한미분 = 아톰구하기

adaboost로 160000개 특징을 6000개로 줄임 → 차원축소

딥러닝 필터와 커널과 윈도우 차이?

12 x 4 = 3 → 12=?, 4=윈도우(필터, 커널), 3=특성맵, x=합성곱

 

4) TMI

인공지능 마술로 생각하지 마세요

James Gosling 왈 JAVA는 망치와 못이다..?

엉터리체온계 경로 여쭤보기

사람얼굴인식으로 체온 쟤는 법 진짜 있음?

깃허브액션 자동배포를 제대로 안해서 카카오가 멈춤

⇒ 있긴 하니까 복구는 함 → 업데이트 안한건가?

HTML의 역사? → XML(개선) ⇒ 공인인증서

 

2. 코드

canny 패키지

init

from canny.views import MenuController
from util.common import Common
LENNA = "Lenna.png"
SOCCER = "<https://docs.opencv.org/4.x/roi.jpg>"
line = "<http://amroamroamro.github.io/mexopencv/opencv_contrib/fast_hough_transform_demo_01.png>"
HAAR = "haarcascade_frontalface_alt.xml"
GIRL = "girl.jpg"
GIRL_SIDE = ""
FAMILY = "family"
CAT = "cat.jpg"
GIRL_TURN = ""
if __name__ == '__main__':
    api = MenuController()
    while True:
        menus = ["종료", "원본보기", "그레이스케일", "엣지검출", "직선검출", "얼굴인식", "모자이크", "얼굴추출"]
        menu = Common.menu(menus)

        if menu == "0":
            api.menu_0(menus[0])
            break
        elif menu == "1": api.menu_1(menus[1], LENNA)
        elif menu == "2": api.menu_2(menus[2], SOCCER)
        elif menu == "3": api.menu_3(menus[3], SOCCER)
        elif menu == "4": api.menu_4(menus[4], line)
        elif menu == "5": api.menu_5(menus[5], HAAR, GIRL)
        elif menu == "6": api.menu_6(menus[6], CAT)
        else:
            print(" ### 해당 메뉴 없음 ### ")

view

from matplotlib import pyplot as plt
from PIL import Image
import cv2 as cv
import numpy as np

from canny.models import Executelambda
import requests
from io import BytesIO
from const.crawler import HEADERS
from util.dataset import Dataset

class MenuController(object):
    @staticmethod
    def menu_0(*params):
        print(params[0])

    @staticmethod
    def menu_1(*params):
        print(params[0])
        img = Executelambda("IMAGE_READ", params[1])
        print(f'cv2 버전 {cv.__version__}')  # cv2 버전 4.6.0
        print(f' Shape is {img.shape}')
        cv.imshow('Gray', img)
        cv.waitKey(0)
        cv.destroyAllWindows()

    @staticmethod
    def menu_2(*params):
        img = Executelambda("URL", params[1])
        gray = Executelambda("gray_scale", img)
        plt.imshow(Executelambda("IMAGE_FROM_ARRAY", gray))
        plt.show()

    @staticmethod
    def menu_3(*params):
        img = Executelambda("URL", params[1])
        edges = cv.Canny(img, 100, 200)
        print(f"image type: {type(img)}")
        plt.subplot(121), plt.imshow(img, cmap='gray')
        plt.title('Original Image'), plt.xticks([]), plt.yticks([])
        plt.subplot(122), plt.imshow(edges, cmap='gray')
        plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
        plt.show()

    @staticmethod
    def menu_4(*params):
        img = Executelambda("URL", params[1])
        edges = cv.Canny(img, 100, 200)
        lines = cv.HoughLinesP(edges, 1, np.pi / 180., 120, minLineLength=50, maxLineGap=5)
        dst = cv.cvtColor(edges, cv.COLOR_GRAY2BGR)
        if lines is not None:
            for i in range(lines.shape[0]):
                pt1 = (lines[i][0][0], lines[i][0][1])
                pt2 = (lines[i][0][2], lines[i][0][3])
                cv.line(dst, pt1, pt2, (255, 0, 0), 2, cv.LINE_AA)
        plt.subplot(121), plt.imshow(edges, cmap='gray')
        plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
        plt.subplot(122), plt.imshow(dst, cmap='gray')
        plt.title('Canny'), plt.xticks([]), plt.yticks([])
        plt.show()

    @staticmethod
    def menu_5(*params):

        # 오리지널 사진
        dt = Dataset()
        girl = Executelambda("IMAGE_READ-PLT", params[2])
        plt.subplot(151), plt.imshow(Image.fromarray(girl))
        plt.title('Original'), plt.xticks([]), plt.yticks([])

        # 회색 사진
        girl_gray = Executelambda("gray_scale", girl)
        plt.subplot(152), plt.imshow(Image.fromarray(girl_gray))
        plt.title('Gray'), plt.xticks([]), plt.yticks([])

        # 엣지 사진
        edges = cv.Canny(girl, 10, 100)
        plt.subplot(153), plt.imshow(edges, cmap='gray')
        plt.title('Edge'), plt.xticks([]), plt.yticks([])

        # 라인 사진
        lines = cv.HoughLinesP(edges, 1, np.pi / 180., 10, minLineLength=50, maxLineGap=5)
        dst = cv.cvtColor(edges, cv.COLOR_GRAY2BGR)
        if lines is not None:
            for i in range(lines.shape[0]):
                pt1 = (lines[i][0][0], lines[i][0][1])
                pt2 = (lines[i][0][2], lines[i][0][3])
                cv.line(dst, pt1, pt2, (255, 0, 0), 2, cv.LINE_AA)
        plt.subplot(154), plt.imshow(dst, cmap='gray')
        plt.title('Line'), plt.xticks([]), plt.yticks([])

        # 하르 사진
        haar = cv.CascadeClassifier(dt.context+params[1])
        face = haar.detectMultiScale(girl, minSize=(150, 150))
        if len(face) == 0:
            print("얼굴인식 실패")
            quit()
        for(x,y,w,h) in face:
            print(f"얼굴 좌표 : {x},{y},{w},{h}")
            red = (255,0,0)
            cv.rectangle(girl, (x,y), (x+w, y+h), red, thickness=10)
        plt.subplot(155), plt.imshow(girl, cmap='gray')
        plt.title('Harr'), plt.xticks([]), plt.yticks([])

        plt.show()

    @staticmethod
    def menu_6(*params):
        pass

model

from io import BytesIO
import numpy as np
import requests
from PIL import Image
import matplotlib.pyplot as plt
from const.crawler import HEADERS
import cv2 as cv

from util.dataset import Dataset

def Executelambda(*params):
    cmd = params[0]
    target = params[1]
    ds = Dataset()
    if cmd == "IMAGE_READ-CV":
        return (lambda x : cv.imread(ds.context + x))(target)
    elif cmd == "IMAGE_READ-PLT":
        return (lambda x : cv.cvtColor(cv.imread(ds.context + x), cv.COLOR_BGR2RGB))(target)
    elif cmd == "gray_scale":
        return (lambda x : x[:, :, 0] * 0.114 + x[:, :, 1] * 0.587 + x[:, :, 2] * 0.229)(target)
    elif cmd == "URL":
        res = requests.get(params[1], headers=HEADERS)
        img = np.array(Image.open(BytesIO(res.content)))
        return img
    elif cmd == "IMAGE_FROM_ARRAY":
        return (lambda x : Image.fromarray(x))(target)

 

3. 하루마무리

어제치 TIL을 안써버렸다..

 

오늘치 커밋도 최신화 못한 채 집에 와버렸다..

 

오늘도 12시 안에 못자버렸다.........

댓글