블로그 이미지
devtang
Instagram : @taebr0 devtaehyeong@gmail.com

calendar

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

Notice

2020. 3. 5. 16:50 Python

몇가지 라이브러리와 파이썬을 이용하여 크롤링하는 예제를 돌려보겠습니다.

 

크롤링(Crawling)이란?

웹 상에 존재하는 갖가지 컨텐츠를 수집하는 작업으로, 다양한 프로그램을 만들 수 있습니다.

예를 들어, 인터넷에 존재하는 이미지 파일을 하나하나 저장하기 번거롭습니다.

크롤링을 이용하면 간단한 코드로 짧은시간에 내가원하는 검색어의 이미지를 가져올 수 있습니다.

 

저는 딥러닝 학습을 위해 많은 양의 이미지가 필요했었는데 이때 자주 이용한 방법이 바로 크롤링입니다.

이것 말고도, 맛집 블로그 링크들을 한번에 모으던가 원하는 사이트목록을 빠른시간에 가져올 수 있는게 큰 장점입니다.

 

마스크 착용 유무를 판단하는 학습 데이터가 필요했습니다.

이렇게 실시간으로 사진이 폴더에 저장됩니다.

 

우선 크롤링에 필요한 import 목록입니다.

from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
from urllib.parse import quote_plus

urlopen은 파이썬을 설치할 때 기본적으로 설치되는 라이브러리입니다.

혹시모르니 필요한 라이브러리를 pip명령어를 이용하여 cmd창에서 설치해주도록 합시다.

 

pip install beautifulsoup4
pip install requests

bequtifulsoup 라이브러리는 HTML 및 XML 파일에서 데이터를 가져 오는 Python 라이브러리입니다. 

이 라이브러리를 이용하여 조금더 편하게 정보를 가져올 수 있습니다.

 

우선 네이버 이미지를 긁어모으기 위해서 네이버 url을 들여다보면

요즘 문제가 심각한 코로나에대해 검색해봤습니다. 또 다른 검색어로 검색해보겠습니다.

 

치킨이 먹고싶네요. 아무튼 위에 두 검색한 url을 들여다보면 

https://search.naver.com/search.naver?where=image&sm=tab_jum&query= 라는 주소에

치킨, 코로나 만 바뀐것을 알 수 있습니다.

 

baseurl 을 위의 주소로 두고, 우리가 원하는 검색어의 이미지를 크롤링하기 위하여 뒤에 검색어는

파이썬 실행시에 입력하도록 plusurl이라는 변수로 생성해줍니다.

 

baseUrl = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='
plusUrl = input('검색어를 입력하세요 : ')
# url = baseurl + 검색어
url = baseUrl + quote_plus(plusUrl)
html = urlopen(url)
soup = bs(html, "html.parser")
img = soup.find_all(class_='_img')

 baseUrl과 검색어의 변수 plusUrl을 더하여 원하는 검색된 페이지로 접근합니다.

이런식으로 html을 열어서 이미지의 경로를 받아옵니다.

 

n = 1
for i in img:
    imgUrl = i['data-source']
    with urlopen(imgUrl) as f:
        with open('./img/' + plusUrl + str(n)+'.jpg','wb') as h: # w - write b - binary
            img = f.read()
            h.write(img)
    n += 1
print('다운로드 완료')

네이버 이미지는 한페이지에 50개의 이미지만 생성되므로 보통 이미지가 다운로드되면 50개까지 크롤링이 가능합니다.

 

아래는 전체 소스 코드입니다.

from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
from urllib.parse import quote_plus

baseUrl = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='
plusUrl = input('검색어를 입력하세요 : ')
# 한글 검색 자동 변환
url = baseUrl + quote_plus(plusUrl)
html = urlopen(url)
soup = bs(html, "html.parser")
img = soup.find_all(class_='_img')

n = 1
for i in img:
    imgUrl = i['data-source']
    with urlopen(imgUrl) as f:
        with open('./img/' + plusUrl + str(n)+'.jpg','wb') as h: # w - write b - binary
            img = f.read()
            h.write(img)
    n += 1
print('다운로드 완료')

 

간단한 파이썬 코드로 네이버 이미지를 빠른시간에 많이 저장할 수 있습니다.

마지막으로 구현 영상입니다.

youtu.be/yl36J0dXS2w

 

 

네이버 이미지 가져오는 방법이었습니다. 감사합니다.

posted by devtang
2020. 3. 2. 17:25 Raspberry Pi

 

EAR(Eye Aspect ratio)알고리즘을 이용한 운전자 졸음운전 방지 시스템 입니다.

 

구현 영상

 

EAR 알고리즘

Soukupová와 Čech의 2016 년 논문인 Facial Landmarks를 사용한 Real-Time Eye Blink Detection 의 작업을 기반으로  EAR ( eye aspect ratio) 관계를 반영하는 방정식을 도출 할 수 있습니다.

 

 

 

눈을 감게 되면 눈의 세로 비율이 작아지고, EAR 비율역시 작아집니다. 사람이 깜박이면 눈의 종횡비가 급격히 감소하여 0에 가까워집니다. 사람이 졸리면 눈을 감거나 눈을 조그마하게 뜨는 행동을 하게 되므로 EAR값을 이용하여 주기적으로 낮아지면 알람을 울리게 하는 졸음감지 시스템을 구현할 수 있습니다.

 

def eye_aspect_ratio(eye):
#눈에 랜드마크 좌표를 찍어서 EAR값을 예측합니다.
	A = dist.euclidean(eye[1],eye[5]) 
	B = dist.euclidean(eye[2],eye[4])
	C = dist.euclidean(eye[0],eye[3])
	
	ear = (A+B) / (2.0 * C)
	return ear

 

또한 평소 눈의 THRESH값을 0.3정도로 설정해놓고 눈을 감게되면 EAR비율이 작아지므로 ALARM이 울리게 됩니다. 

# 눈의 EAR의 THRESH 기본값을 0.3으로 설정합니다.
EYE_AR_THRESH = 0.3
EYE_AR_CONSEC_FRAMES = 48
# 프레임 카운터와 부울을 초기화하는 데 사용
# 알람이 울리면 표시
counter = 0
ALARM_ON = false

 

 

OpenCV의 drawContours 함수를 이용하여 눈 주변에 선을 실시간으로 그려줍니다.

   #외곽선으로 인식된 눈을 그려줍니다(drawContours함수이용)
		leftEyeHull = cv2.convexHull(leftEye)
		rightEyeHull = cv2.convexHull(rightEye)
		cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
		cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

 

눈을 인식해야 하므로 68_face_landmark.dat 파일을 이용하여 예제를 실행합니다.

 

정상적으로 구동이 되는것을 확인했습니다. 라즈베리파이에서 실시간으로 돌려봤지만

위에 동영상을 보시면 프레임이 상당히 낮습니다.

 

읽어주셔서 감사합니다.

 

posted by devtang
2020. 2. 25. 14:00 Raspberry Pi

*참고한 사이트는 게시글 하단에 남겨놓겠습니다.

 

저번 게시물에서 얼굴의 68개의 특징점을 잡아낸 알고리즘을 이용한 예제를 실행해봤습니다.

이번에는 5개의 랜드마크를 추출하는 알고리즘을 사용했습니다.

 

 

68개의 랜드마크를 추출하는 방식과 달리 ,이번 알고리즘은 

왼쪽 눈 2점, 오른쪽 눈 2점, 코 1점을 검출하여, 라즈베리파이에서 보다 더 나은 속도를 보여줍니다.

속도는 68개 추출에 비해 8-10% 향상되었으며, 잠재적으로 정확성은 조금 떨어질 수 있다고 합니다.

인식률이 상당히 좋습니다. 라즈베리파이에서 이정도 속도만 나와도 감사할 따름입니다...

실시간으로 웹캠을 통해 얼굴의 특징점이 인식됩니다.

또한

68 포인트 랜드마크 데이터 파일은 99.7MB정도였지만

5 포인트 랜드마크 데이터 파일은 9.2MB로 기존 파일에 비해 약 10배 정도 작아졌습니다.

 

구성환경으로는 전 게시물과 동일합니다.

Raspberry Pi 3B+

Picamera

OS : Raspbian Stretch 9.11

OpenCV, imutils, dlib,라이브러리 설치

 

소스코드입니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# USAGE
 
# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import time
import dlib
import cv2
 
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p""--shape-predictor", required=True,
    help="/home/pi/Desktop/faster_facial_landmarks/shape_predictor_5_face_landmarks.dat")
args = vars(ap.parse_args())
 
# initialize dlib's face detector (HOG-based) and then create the
# facial landmark predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])
 
# initialize the video stream and sleep for a bit, allowing the
# camera sensor to warm up
print("[INFO] camera sensor warming up...")
#vs = VideoStream(src=0).start()
vs = VideoStream(usePiCamera=True).start() # Raspberry Pi
 
# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream, resize it to
    # have a maximum width of 400 pixels, and convert it to
    # grayscale
    frame = vs.read()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
    # detect faces in the grayscale frame
    rects = detector(gray, 0)
 
    # check to see if a face was detected, and if so, draw the total
    # number of faces on the frame
    if len(rects) > 0:
        text = "{} face(s) found".format(len(rects))
        cv2.putText(frame, text, (1020), cv2.FONT_HERSHEY_SIMPLEX,
            0.5, (00255), 2)
 
    # loop over the face detections
    for rect in rects:
        # compute the bounding box of the face and draw it on the
        # frame
        (bX, bY, bW, bH) = face_utils.rect_to_bb(rect)
        cv2.rectangle(frame, (bX, bY), (bX + bW, bY + bH),
            (02550), 1)
 
        # determine the facial landmarks for the face region, then
        # convert the facial landmark (x, y)-coordinates to a NumPy
        # array
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)
 
        # loop over the (x, y)-coordinates for the facial landmarks
        # and draw each of them
        for (i, (x, y)) in enumerate(shape):
            cv2.circle(frame, (x, y), 1, (00255), -1)
            cv2.putText(frame, str(i + 1), (x - 10, y - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.35, (00255), 1)
 
    # show the frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1& 0xFF
 
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
 
# do a bit of cleanup
cv2.destroyAllWindows()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

자세한 소스 코드 내용은, 이곳을 참조하세요.

 

코드 복사후, 동일한 폴더 내에 데이터 파일과 파이썬파일을 넣어줍니다.

(5 포인트 얼굴 랜드마크 추출 데이터 파일은 하단의 참조사이트에서 받을 수 있습니다.)

 

저는 Desktop 에 faster_facial_landmarks 라는 폴더를 생성하여 넣어주었습니다.

터미널에 명령어를 입력해줍니다.

1
2
pi@raspberrypi:~/Desktop/faster_facial_landmarks $ python faster_facial_landmarks.py -shape_predictor_5_face_landmarks.dat
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

이번 게시물은 5개의 특징점을 잡아내는 예제를 실행해봤습니다.

다음엔 졸음운전을 감지하는 시스템(?) 을 포스팅 하도록 하겠습니다.

 

서투른 글 읽어주셔서 감사합니다.

 

참고사이트

(Faster) Facial landmark detector with dlib

 

(Faster) Facial landmark detector with dlib - PyImageSearch

In this tutorial you'll learn how to use dlib's 5-point facial landmark model, over 10x smaller and 8-10% faster than the original 68-point facial landmark detector.

www.pyimagesearch.com

 

posted by devtang
2020. 2. 25. 12:54 Raspberry Pi

*참고한 사이트는 게시글 하단에 남겨놓겠습니다.

 

이번에 게시할 내용은 바로 dlib 와 OpenCV을 이용한 얼굴의 특징점을 찾아내는 예제입니다.

 

위와같이 얼굴의 특징점을 실시간으로 잡아주는 예제를 실행해봤습니다.

 

Facial Landmarks?

 

 

68개의 특징점을 추출한 포인트

사람의 얼굴에 특징점을 찍어낸 방법입니다.

Face Landmark estimation 알고리즘의 원리는 2014년도에 발명된 접근 방식입니다.

이것을 이용하여 카메라를 이용한 다양한 어플리케이션을 만들수도 있습니다.

 

저는 이것을 라즈베리파이로 실시간 캠영상을 받아, 얼굴에 랜드마크를 표시하는 예제를 실행해봤습니다.

실행한 환경으로는

 

Raspberry Pi 3B+

Picamera

OS : Raspbian Stretch 9.11

OpenCV, imutils, dlib,라이브러리 설치

(라즈베리파이 세팅, 라이브러리 설치 방법 등은 추후에 포스트할 예정입니다.)

 

shape_predictor_68_face_landmarks.dat 파일은 게시물 하단의 참고사이트나 메일로 연락주세요.

 

제가 실행해본 소스 코드입니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# USAGE
 
# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import datetime
import argparse
import imutils
import time
import dlib
import cv2
 
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p""--shape-predictor", required=True,
    help="path to facial landmark predictor")
ap.add_argument("-r""--picamera", type=int, default=-1,
    help="whether or not the Raspberry Pi camera should be used")
args = vars(ap.parse_args())
 
# initialize dlib's face detector (HOG-based) and then create
# the facial landmark predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])
 
# initialize the video stream and allow the cammera sensor to warmup
print("[INFO] camera sensor warming up...")
vs = VideoStream(usePiCamera=args["picamera"> 0).start()
 
# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream, resize it to
    # have a maximum width of 400 pixels, and convert it to
    # grayscale
    frame = vs.read()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
    # detect faces in the grayscale frame
    rects = detector(gray, 0)
 
    # loop over the face detections
    for rect in rects:
        # determine the facial landmarks for the face region, then
        # convert the facial landmark (x, y)-coordinates to a NumPy
        # array
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)
 
        # loop over the (x, y)-coordinates for the facial landmarks
        # and draw them on the image
        for (x, y) in shape:
            cv2.circle(frame, (x, y), 1, (00255), -1)
      
    # show the frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1& 0xFF
 
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
 
# do a bit of cleanup
cv2.destroyAllWindows()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

소스코드의 자세한 내용은 , 이곳을 참조하세요.

 

소스코드를 저장한후 꼭 소스파일과 landmark 데이터 파일이 한 폴더 내에 있어야합니다.

 

터미널 창을 열어 명령어를 입력해줍니다.

1
pi@raspberrypi:~/Desktop $ python real_landmarks.py -shape_predictor_68_face_landmarks.dat
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

성공적으로 감지가 됩니다!!

 

라즈베리파이에서 구현시 프레임이 저하되긴 하지만 활용할만한 알고리즘인것 같습니다. 

다음 게시물엔 라즈베리파이에서 조금더 효율적으로 인식이되는 방법에대해 포스팅 할 예정입니다.

서투른 글 읽어주셔서 감사합니다.

참고사이트

기계 학습(Machine Learning, 머신러닝)은 즐겁다! Part 4

 

기계 학습(Machine Learning, 머신 러닝)은 즐겁다! Part 4

딥러닝(Deep Learning)을 사용한 최신 얼굴 인식(Face Recognition)

medium.com

Real-time facial landmark detection with OpenCV, Python, and dlib

 

Real-time facial landmark detection with OpenCV, Python, and dlib - PyImageSearch

In this tutorial, I demonstrate how to detect facial landmarks in video streams in real-time using OpenCV, Python, and dlib.

www.pyimagesearch.com

 

posted by devtang
prev 1 next