ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [익은 토마토 선별하기] 1. 토마토 사진 구하기
    AI/객체인식 2022. 5. 19. 00:00

    토마토를 인식하기 위해서 토마토 사진을 구글 이미지를 통해 구하려고 한다.

     

    하나하나 이미지를 구해면 시간이 오래 걸리기 때문에 '크롤링'을 이용해서 이미지를 구하려고 한다.

     


    크롤링 구현

    크롤링은 인터넷에서 검색하면 코드가 잘 나와있다.

    코드를 일부 수정해서 크롤링을 진행했다.(파이참으로 실행함)

     

    아래 코드는 수정한 크롤링 코드다.

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    import time
    import urllib.request
    import os
    from multiprocessing import Pool
    
    def createDirectory(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            print("Error: Failed to create the directory.")
    
    def crawling_img(name):
    
        driver = webdriver.Chrome()
        driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&authuser=0&ogbl")
        elem = driver.find_element(By.XPATH, '//*[@id="sbtc"]/div/div[2]/input')
        elem.send_keys(name)
        elem.send_keys(Keys.RETURN)
    
        print(name + "검색 중...")
        time.sleep(4)
    
        SCROLL_PAUSE_TIME = 1.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,".mye4qd").click()
                except:
                    break
            last_height = new_height
    
        imgs = driver.find_elements(By.CSS_SELECTOR, ".rg_i.Q4LuWd")
        dir = "./imgs/" + name
    
        createDirectory(dir) #폴더 생성
        count = 1
    
        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)
        for img in imgs:
            try:
                img.click()
                time.sleep(2)
                imgUrl = driver.find_element(By.XPATH, '/html/body/div[3]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div[3]/div/a/img').get_attribute("src")
                path = dir + "/"
                urllib.request.urlretrieve(imgUrl, path + str(count) + ".png")
                print(name + str(count) + ".png")
                count = count + 1
                # if count >= 260:
                #     break
            except:
                pass
        driver.close()
    
    
    searchs = ["검색어1", "검색어2"] #검색어 입력!
    
    if __name__=='__main__':
        pool = Pool(processes=4) # 4개의 프로세스를 사용합니다.
        pool.map(crawling_img, searchs) # pool에 일을 던져줍니다.

     

    코드를 설명하자면,

    다운로드하고 싶은 검색어를 아래 코드에 입력한다.

    searchs = ["검색어1", "검색어2"]

    검색어를 입력하고 코드를 실행하면 멀티 프로세서가 동작하고 각각 검색어에 해당하는 원본 이미지가 동시에 다운로드된다.

     

    주의할 점은 네트워크 환경에 따라 동작이 잘 안 될 수 있다.

    이럴 경우 아래 시간을 조절하면 된다.

    SCROLL_PAUSE_TIME = 1.5
    
    time.sleep(2)

     


    크롤링 실행

    크롤링이 실행 중인 모습이다.

     


    크롤링 후 사진 선별

    구별하기 힘들고 토마토와 관련이 없는 사진을 선별했다.

     

    다음 시간에는 roboflow라는 사이트를 이용해서 라벨링을 할 예정이다.


    토마토 사진을 얻다!!!

    직접 찍은 토마토 사진과 영상을 구해주신 OpenCowork 대표님 감사합니다.

    라벨링을 하려고 했는데 고화질 토마토 사진을 구해주셔서

    이 사진으로 라벨링을 할 예정이다.

Designed by Tistory.