코딩 테스트 - 2

Kevin Lee·2020년 6월 29일
0

스트라드비젼 인턴

목록 보기
3/12

Test 3

3번째 테스트는 OpenCV를 쓸 수있는지에 중점을 둔 문제인거 같았다. 학교에서 Computer Vision을 들을때 OpenCV를 써봤어서 문제없이 쉽게 푼거 같았다. waitKey를 써서, 스페이스를 눌렀을때 pause/play, "<"를 눌렀을때 10 frame 뒤로, ">" 는 10 frame 앞으로 이동 그리고 "s" 버튼은 current frame을 저장 한다. 그런데 예로 주신 영상 중에 1초만 영상을 read하고 꺼지는 이유가 있었는데, 영상이 보호되있는건지 이상한 오류가 발생 하였다. (영상이 상업 플레이어에서는 잘 재생되는데, openCV에선 잘안되는 이유를 말해라고 테스트에 명시되있었다.)


	Mat frame;
	ostringstream name;
	int capture[256] = { 0 };
	VideoCapture cap("path_to_source");
	double fps = cap.get(CAP_PROP_FPS);
	int framecount = cap.get(CAP_PROP_FRAME_COUNT);
	int play = 1;
	int index = 0;
	printf("FPS = %f\n", fps); //frame per second 
	printf("frame count %d\n", framecount); //영상에 총 몇개의 frame이 있는지


	if (cap.open("path_to_source") == 0) {
		printf("Can't read Video!\n");
		return 0;
	}

	while (1) {
		if (cap.grab() == 0) {
			printf("end of the video!\n");

			break;
		}
		cap >> frame;
		int current = cap.get(CAP_PROP_POS_FRAMES); //current position
		//텍스트 출력
		putText(frame, format("%d/%d", current, framecount), Point(10, 40), FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 255, 255));
		imshow("Window", frame);
		int k = waitKey(fps);
		
		if (k == 32) { //press spacebar to play or pause
			if (play == 1) {
				waitKey(0);
				play = 0;
			}
			waitKey(fps);
			play = 1;
		}
		if (k == 44) { //'<' to go back 1 frame
			cap.set(CV_CAP_PROP_POS_FRAMES, current - 10 );
		}
		if (k == 46) { //'>' to go forward 1 frame
			cap.set(CV_CAP_PROP_POS_FRAMES, current + 10);
		}
		if (k == 115) {//if key is 's' save the current frame

			capture[index] = current;
			index++;
			
		}
		
	}
	int n = sizeof(capture) / sizeof(capture[0]);
	printf("%d\n", n);
	for (int i = 0;i < n;i++) {
		printf("%d\n", capture[i]);
		cap.set(CAP_PROP_POS_FRAMES, capture[i]);
		cap >> frame;
		name << "path" << capture[i] << ".jpg";
		imwrite(name.str(), frame); //프레임 저장.
	}
	

Test 4

인터넷 크롤링 문제였다. Google, Flickr에서 원하는 크기 이상의 이미지 크롤러 그리고 youtube 영상 크롤러 였다.

Flickr랑 youtube 영상은 크롤링을 못했지만, 구글 이미지는 크롤링에 성공하였다. Selenium, BeautifulSoup 같은 크롤링 툴들을 써서 크롤링을 하였다. 솔직히 크롤링은 어떤 알고리즘을 쓰는것 보다 경로를 찾는 노가다(?)이여서 xpath나, css 이름을 검사 페이지에서 찾는 것을 열심히 하면 누구나 할 수 있는 것 같다. 구글과 달리, Flickr는 이미지 api를 제공해주는 것 같은데, 이거는 등록해서 써야되기 때문에 시간상 패스했다. Youtube도 링크는 가져올 수 있겠지만, 원본 영상은....

    print("Enter Keyword:")
    query = input()
    PATH = 'your_path_here/chromedriver.exe'
    wd = webdriver.Chrome(executable_path=PATH)
    google_search = "https://www.google.com/search?q={q}&tbm=isch"
    wd.get(google_search.format(q=query))
    time.sleep(2)
    image_sizes = wd.find_elements_by_css_selector('div.isv-r')

    count = 0
    for image_size in image_sizes:
        try:
            if int(image_size.get_attribute('data-ow')) > 500 and int(image_size.get_attribute('data-oh')) > 500:
                image_size.click()
                time.sleep(1)
                actual = wd.find_element_by_xpath('//*[@id="Sva75c"]/div/div/div[3]/div[2]/c-wiz/div[1]/div[1]/div/div[2]/a/img')
                
                
                pic = actual.get_attribute('src')
                
              
                time.sleep(1)
                jpg = urlopen(pic).read()
             
                
                filename = query + str(count)+'.jpg'
                with open("your_path_here/"+filename,"wb") as f:
                    f.write(jpg) 
                count += 1

        except Exception:
            continue

selenium을 이용해서 chromedriver로 실행해서 image crawling을 하였다. 중간중간 sleep을 줘야지 페이지 로딩하는데 시간을 줄 수 있다. 원하는 사이즈는 위 코드에선 임의로 500x500사이즈보다 큰 이미지들만 저장하는것으로 만들었다. 위 코드는 구글이 또 언제 div이름을 바꿀지 모르기 때문에 잘 작동을 안 할 수있다.

profile
🧠🦾❤ https://github.com/to2915ny

0개의 댓글