[2022 국민대학교 겨울 인공지능 특강] 4주차 5일 학습 내용

하지원·2022년 2월 8일
0
  • Image crawling
    딥러닝 모델을 훈련시키려면 데이터가 많이 필요하다. 인터넷에서 특정 이미지를 1만개 이상 다운받기에는 시간이 너무 오래걸리고, 그렇다고 컴퓨터에 저장된 이미지 데이터를 회전하거나 반전하는 등으로 변형을 해서 데이터 증식(data augmentation)을 하는 것도 시간이 오래걸린다. 그래서 컴퓨터가 인터넷에서 수많은 이미지들을 조건에 맞춰 직접 다운받도록 코딩하는 방법이 있는데, 이를 이미지 크롤링이라 부른다.

이미지 크롤링을 하기 위해서는 크롤링 혹은 스크레이핑에 필요한 패키지가 필요한데, beautifulsoup라는 것이 있다.

Anaconda에서 다음 코드를 입력하면 된다.

pip install beautifulsoup4

또한 검색 엔진 링크와 검색어 주소를 불러오기 위해 다음 모듈도 필요하다.
from urllib.request import urlopen
from urllib.parse import quote_plus

일반적으로 이미지 크롤링은 다음과같이 진행한다.

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='
query = "김종국"
url = baseUrl + quote_plus(query)
html = urlopen(url)
soup = bs(html, "html.parser")
img = soup.find_all(class_='_img')
cnt = 1
for i in img:
    imgUrl = i['data-source']
    print(imgUrl)
    if cnt <= 20:
		with urlopen(imgUrl) as f:
  			with open('./custom_dataset/train/jongkook/' + query + str(cnt) + '.jpg','wb') as h:
    			img = f.read()
    			h.write(img)
    else:
		with urlopen(imgUrl) as f:
  			with open('./custom_dataset/val/jongkook/' + query + str(cnt) + '.jpg','wb') as h:
    			img = f.read()
    			h.write(img)
    if cnt == 30:
  		break
    cnt += 1
profile
국민대 전자공학부, 서강대학교 석사과정, 크래프톤 정글 2기

0개의 댓글