[AI 앱 개발] v2v: value to value (이미지 크롤링)

danbibibi·2022년 8월 10일
0

이미지 크롤링

프로젝트를 진행하기 위해 다음과 같은 방법으로 데이터를 수집하였다.

반 고흐의 그림은 kaggle에 존재하기에 총 2~4번 데이터 셋만 별도로 크롤링했다.

  1. 반 고흐의 그림 (230장)
  2. 반 고흐 그림에 대응될 풍경 사진 (230장)
  3. 에곤 실레 그림 (466장)
  4. 에곤 실레 그림에 대응될 사람의 상반신, 얼굴, 전체 사진 (466장)

먼저 구글 이미지를 크롤링하는 라이브러리를 깃허브에서 발견해 사용했다. 사용법을 한국어로 설명해 둔 오토코더 유튜브도 참고했다.

!pip install git+https://github.com/Joeclinton1/google-images-download.git

from google_images_download import google_images_download   #importing the library

def googleImageCrawling(keyword, limit):
    response = google_images_download.googleimagesdownload()   #class instantiation

    arguments = {"keywords": keyword,"limit": limit,
               "print_urls":True, "chromedriver":"./chromedriver", "format":"jpg"}   #creating list of arguments
    paths = response.download(arguments)   #passing the arguments to the function
    print(paths)   #printing absolute paths of the downloaded images

keyword = input("키워드 입력해주세요(복수 선정 시 , 붙여서 입력해주세요!) : ")
limit = input("이미지 개수를 입력해주세요 : ")

googleImageCrawling(keyword, int(limit))

그러나 이 라이브러리는 최대 100장까지만 크롤할 수 있는 문제가 있어, 직접 구글 이미지를 크롤하는 방법 찾아서 진행했다. 유튜브 조코딩의 구글 이미지 크롤 영상을 참고해서 만들었다.

# 셀레니움을 활용해 구글 이미지 크롤하는 코드
# https://www.youtube.com/watch?v=1b7pXC1-IbE&ab_channel=%EC%A1%B0%EC%BD%94%EB%94%A9JoCoding
# 유튜브 조코딩 참조

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib.request
import random
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&authuser=0&ogbl")

elem = driver.find_element(By.NAME, "q")
elem.send_keys("landscape photograph") # 검색어는 여기에 집어넣기
elem.send_keys(Keys.RETURN)

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        try:
            driver.find_element_by_css_selector("input.mye4qd").click()
        except:
            break
    last_height = new_height


for i in range(100): # 여기에 몇개를 크롤하고 싶은지 적기
    try:
        driver.find_elements(By.CSS_SELECTOR, ".rg_i.Q4LuWd")[i].click()
        time.sleep(random.uniform(2,3))

        opener=urllib.request.build_opener()
        opener.addheaders=[('User-Agent','본인의 User-Agent')]
        urllib.request.install_opener(opener)      
        
        imgUrl = driver.find_element(By.CSS_SELECTOR, ".n3VNCb.KAlRDb").get_attribute("src")
        urllib.request.urlretrieve(imgUrl, "./image_download/view_{}.jpg".format(i))
    except:
         pass

크롤 후 모은 사진에 대해 다음 프로세스를 진행했다.
1) 중복 사진 제거 프로그램을 활용해 중복된 사진 제거
2) 이미지 확장자 통일 및 연속적인 이름으로 변경

profile
블로그 이전) https://danbibibi.tistory.com

0개의 댓글