{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"32023ecdfbc933ff7b0956bec12e925484c8999e"},"cell_type":"markdown","source":"### 케라스 불러오기"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"90d2a901607fe6501b10b5b8c77c2107508705ac"},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport cv2, random\nfrom matplotlib import pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9baec205aca631e634cf723375bb885e500a35b8"},"cell_type":"code","source":"# numpy random 발생기 지정.\nnp.random.seed(1339)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f2c9167d6078a5f4313f134634aa53382b88e23f"},"cell_type":"markdown","source":"> ## 이미지 확인하기\n* 총 몇장일까?\n* 이미지의 크기는? "},{"metadata":{"trusted":true,"_uuid":"561267a27297b942dcc0773ea88d33d4c59a28fc"},"cell_type":"code","source":"TRAIN_DIR = '../input/train/'\nTEST_DIR = '../input/test/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"685386609223105ba4ad9e26f410b6d731ffb2bf"},"cell_type":"code","source":"img = cv2.imread('../input/train/dog.3.jpg')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nplt.imshow(img)\nprint(img.shape)\nprint(len(os.listdir(TRAIN_DIR))) # 25001장 \nprint(len(os.listdir(TEST_DIR)))  # 12501장","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"14aebcc7f78e7ec208f39eb48795fcdb48a2e5b9"},"cell_type":"markdown","source":"### 하나의 이미지는 어떤 정보를 가지고 있을까?"},{"metadata":{"trusted":true,"_uuid":"5bd85bc5d0b8ddde3bc667ac2b512681eaa66f55"},"cell_type":"code","source":"print(img.shape)\nimg","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"607628852b1f64adc565fe59e10ffd4538dc1941"},"cell_type":"markdown","source":"## 이미지 폴더 내 리스트 확인\n* 개의 경우는 앞이 dog, 고양이의 경우는 cat이 붙는다.\n* TEST 디렉터리에는 이미지 번호만 있다."},{"metadata":{"trusted":true,"_uuid":"9e9ac57fb7823a030274cb28407c804ff0b45f92"},"cell_type":"code","source":"print(os.listdir(TRAIN_DIR)[:5])\nprint(os.listdir(TEST_DIR)[0:5])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d684a11661ff1d966fc34bbfee906a1527e27dd9"},"cell_type":"markdown","source":"## 이미지별 목록을 갖는 리스트 만들기\n* 전체 이미지 : train_images\n* 개의 이미지 이름 : train_dogs\n* 고양이의 이미지 이름 : train_cats"},{"metadata":{"trusted":true,"_uuid":"381d8da95aea256684df359f27ab92e2c0821e0b"},"cell_type":"code","source":"train_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)] # use this for full dataset\ntrain_dogs =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'dog' in i]\ntrain_cats =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cat' in i]\n\ntest_images =  [TEST_DIR+i for i in os.listdir(TEST_DIR)]\n\nprint(train_images[0:3], train_dogs[0:3], train_cats[0:3])\nprint(test_images[0:3])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"54723903aff16effcb23c3c2ababc1ad6dae62b6"},"cell_type":"code","source":"print(train_images[24990:]) \n#random.shuffle(train_images)  # 이미지를 섞기\n#print(train_images[0:10])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c2ee4f8fe2ab850d5f834f16ba36d9010179e85e"},"cell_type":"markdown","source":"## imread 함수 이해\n* OpenCV을 이용한 이미지 읽기\n* (ex) img = cv2.imread('test.jpg', cv2.IMREAD_COLOR)\n* cv2.IMREAD_COLOR : 1  이미지 파일을 Color로 읽음. 투명한 부분은 무시하며 Default 설정입\n* cv2.IMREAD_GRAYSCALE(0) : 이미지 파일을 Grayscale로 읽음. 실제 이미지 처리시 중간 단계로 많이 사용\n* cv2.IMREAD_UNCHAN**GED(-1) : 이미지 파일을 alpha channel 까지 포함해 읽음"},{"metadata":{"trusted":true,"_uuid":"e58e3c81e0bd0b087a21cb88a4e70342dabb8822"},"cell_type":"code","source":"print(cv2.IMREAD_COLOR)\nprint(cv2.IMREAD_GRAYSCALE)\nprint(cv2.IMREAD_UNCHANGED)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"be026c9488f45ec9bf7590dd2a2ae5b57bb1068e"},"cell_type":"markdown","source":"## cv2.cvtColor 함수 이해\n* 색상 변환할 때 사용. cv2.cvtColor(input_image, flag)\n* ### Convert BGR to HSV\n  *    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n* BGR -> Gray =>  우리는 플래그 cv2.COLOR_BGR2GRAY를 사용\n* BGR -> HSV => cv2.COLOR_BGR2HSV 을 이용\n* BGR -> RGB =>cv2.COLOR_BGR2RGB"},{"metadata":{"trusted":true,"_uuid":"419e2e657db27f01c151f658f936db7b38eb53cb"},"cell_type":"code","source":"print(cv2.COLOR_BGR2RGB)\nprint(cv2.INTER_CUBIC)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2a530759d1d9c303ff63f2c1fda1ab487fbfd9bc"},"cell_type":"markdown","source":"### 이미지 사이즈 조절\n* cv2.resize(원본 이미지, 결과 이미지 크기, 보간법)\n* (예제) dst = cv2.resize(src, dsize=(640, 480), interpolation=cv2.INTER_AREA)\n* cv2.INTER_CUBIC : 바이큐빅 보간법 ( 이미지를 확대하는 경우, 바이큐빅 보간법이나 쌍 선형 보간법을 가장 많이 사용 )"},{"metadata":{"trusted":true,"_uuid":"9b65788bb065a88fba45a4336c7ba630543f2908"},"cell_type":"code","source":"ROWS = 100      # 이미지 세로 \nCOLS = 100      # 이미지 가로\nCHANNELS = 3    # 이미지 채널 수\n\ndef read_image(file_path):\n    img = cv2.imread(file_path, cv2.IMREAD_COLOR) # (1) 컬러 이미지로 읽기\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    # (2) BGR를 RGB로 변경하기\n    return cv2.resize(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC) # (3) 이미지 리사이즈 하기","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a867eb135805a2cb50e17680755305bc7952fd7e"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1c850118021e6d9177106842bd80591d87ee1024"},"cell_type":"code","source":"## 이미지 파일 리스트를 받아, 이미지를 리사이즈하고,\n## 이미지 정보를 0-1 사이의 값으로 바꾸는 것 수행하기\n## 이를 수행한, 반환\ndef prep_data(images):\n    count = len(images)\n    data = np.ndarray((count, ROWS, COLS, CHANNELS), dtype=np.float32)\n\n    for i, image_file in enumerate(images):\n        if i>24490:\n            print(i, image_file)\n        image = read_image(image_file)\n        image = image / 255\n        data[i] = image\n        if i%500 == 0: print('Processed {} of {}'.format(i, count))\n    \n    return data","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2168cf743284de0f8167c6282ef3af9ecd400fe7"},"cell_type":"markdown","source":"### 이미지 전처리 수행\n* 1000장씩 처리 됨을 출력함."},{"metadata":{"trusted":true,"_uuid":"e07eef994028800fc2194c4417a957cf9abcf216"},"cell_type":"code","source":"%%time\n\n#train = prep_data(train_images)\n#test = prep_data(test_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"24ca2481bf8de0166f2107b0da26ce77d19810fc"},"cell_type":"code","source":"#print(\"Train shape: {}\".format(train.shape))\n#print(\"Test shape: {}\".format(test.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"574bff977a0d6e97631c156ec017f778eaa402a6"},"cell_type":"code","source":"## 문제가 있다면 답이 있어야 하므로, 이미지 이름에서 dog, cat를 분류하자.\n#labels = []\n#for i in train_images:\n#    if 'dog' in i:\n#        labels.append(1)\n#    else:\n#        labels.append(0)\n#labels = np.asarray(labels).astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b70ce0736fe63dcba7f7372cfad2f1058cb18c7b"},"cell_type":"markdown","source":"## REF\n* cv2.cvtColor : https://www.programcreek.com/python/example/89426/cv2.cvtColor\n* cv2.resize : https://076923.github.io/posts/Python-opencv-8/ 참조\n"},{"metadata":{"trusted":true,"_uuid":"c2ff83860b7073362fa6ce1be58cbfdc3eec8611"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}