Python/이미지 처리

[Python] 이미지 데이터셋 수집 방법 3가지

seo0seok 2023. 7. 10. 15:54

 

1. roboflow

https://public.roboflow.com/

 

 

2. kaggle

https://www.kaggle.com/datasets

 

 

3. 구글 이미지 크롤링

import ssl
import os
import sys
import time
import urllib.request
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

ssl._create_default_https_context = ssl._create_unverified_context

searchKey = input('Search Keyword : ')

# 저장할 폴더 경로 설정
path = f"./imgs/{searchKey}/images"

try:
    # 중복되는 폴더명이 없다면 생성
    if not os.path.exists(path):
        os.makedirs(path)
    # 중복된다면 문구 출력 후 프로그램 종료
    else:
        print('이전에 같은 [검색어, 이미지 수]로 다운로드한 폴더가 존재합니다.')
        sys.exit(0)
except OSError:
    print('OS error')
    sys.exit(0)

options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&authuser=0&ogbl")
elem = driver.find_element("name", "q")

elem.send_keys(searchKey)
elem.send_keys(Keys.RETURN)

SCROLL_PAUSE_TIME = 1
# 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")
    selector = ".mye4qd"
    if new_height == last_height:
        try:
            driver.find_element(By.CSS_SELECTOR, selector).send_keys(Keys.ENTER)
        except:
            break
    last_height = new_height

images = driver.find_elements(By.CSS_SELECTOR, ".rg_i.Q4LuWd")
print("Total images found:", len(images))

count = 0
for image in images:
    try:
        if count >= 500:
            break
        image.click()
        time.sleep(1)
        xpath = r'//*[@id="Sva75c"]/div[2]/div[2]/div[2]/div[2]/c-wiz/div/div/div/div[3]/div[1]/a/img[1]'
        imgUrl = driver.find_element(By.XPATH, xpath).get_attribute("src")
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
        urllib.request.install_opener(opener)

        urllib.request.urlretrieve(imgUrl, f'{path}/{searchKey}{str(count+1)}.jpg')
        count += 1
        print("Downloaded image", count)
    except Exception as e:
        print('Error:', e)

driver.quit()

  - 구글 이미지 크롤링 코드이다.

  - 코드 실행 후 크롤링할 검색명을 console창에 입력하면 구글 이미지 크롤링이 시작된다.

  - 자동으로 500개까지 크롤링 되게 코딩되어있지만 구글 보안 정책 때문에

    최대 400개 까지만 가능하다.

  - 크롤링 도중 에러가 발생하는 이미지들도 많아 400개를 크롤링하여도 다운로드

    되는 이미지는 그것보다 적다.  

  - 필자는 파이참으로 실행하여 PycharmProjects 폴더에 이미지 폴더가 생성된다.