{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\n\nimport os\nfrom glob import glob\n\nimport cv2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"3efcc6ac4eb9e64b63547ff5316d8baeadc63ec1"},"cell_type":"code","source":"def read_image(path):\n    # OpenCV는 이미지 데이터를 B(lue), G(reen), R(ed) 순서로 읽어오기 때문에,\n    # cv2.cvtColor() 함수를 통해 R(ed), G(reen), B(lue) 순서로 변경한다.\n    image = cv2.imread(path, cv2.IMREAD_COLOR)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7a1b92d4d38899c5e80892ba6bc5c52c743a3025"},"cell_type":"code","source":"# 이미지 파일 경로를 지정한다\ndata_dir = '../input/'\n# data_dir = '~/.kaggle/competitions/state-farm-distracted-driver-detection/'\ntrain_path = data_dir + 'train/c0/'\ntest_path = data_dir + 'test/'\nfilename = 'img_100026.jpg'\n\n# 이미지 데이터 읽어오기\nimage = read_image(train_path + filename)\n\n# 이미지 시각화\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e1839056fbd4d6a8e77622da051432cf86bef86"},"cell_type":"code","source":"# 훈련 데이터 클래스별 예시를 시각화한다\nlabels = ['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9']\ncol_to_kor = {\n    'c0': '안전 운전',\n    'c1': '오른손으로 문자',\n    'c2': '오른손으로 전화',\n    'c3': '왼손으로 문자',\n    'c4': '왼손으로 전화',\n    'c5': '라디오 조작',\n    'c6': '음료수 섭취',\n    'c7': '뒷자석에 손 뻗기',\n    'c8': '얼굴, 머리 만지기',\n    'c9': '조수석과 대화',\n}\nfor label in labels:\n    f, ax = plt.subplots(figsize=(12, 10))\n    files = glob('{}/train/{}/*.jpg'.format(data_dir, label))\n    \n    # 총 9개의 이미지를 시각화한다\n    for x in range(9):\n        plt.subplot(3, 3, x+1)\n        image = read_image(files[x])\n        plt.imshow(image)\n        plt.axis('off')\n    plt.show()\n    print('\\t\\t\\t\\t# {} : {}'.format(label, col_to_kor[label]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6c4a3fce9e4b3d1e1b3b58cc6e324542e0f91ce3"},"cell_type":"code","source":"# 테스트 데이터 예시를 시각화한다\nf, ax = plt.subplots(figsize=(24, 10))\nfiles = glob('{}/test/*.jpg'.format(data_dir))\n    \n# 총 18개의 이미지를 시각화한다\nfor x in range(18):\n    plt.subplot(3, 6, x+1)\n    image = read_image(files[x])\n    plt.imshow(image)\n    plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"74ba4a59c6ced6af3165aace356f4ac844746267"},"cell_type":"code","source":"import pandas as pd\n\n# 파일을 읽어온다\ndriver_list = pd.read_csv('../input/driver_imgs_list.csv')\n\n# 파일의 첫 5줄을 출력한다\ndriver_list.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5ee8be2c344b5b7532929d2776c8205d6a797daa"},"cell_type":"code","source":"import numpy as np\n\n# 운전자 ID 고유값의 개수를 출력한다\nlen(np.unique(driver_list['subject']).tolist())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"592b2f2de21c5d9147392f4dd79976c43146f7ee"},"cell_type":"code","source":"# 운전자별 이미지 데이터를 저장하는 dict를 생성한다\ndriver_to_img = {}\nfor i, row in driver_list.iterrows():\n    driver = row['subject']\n    label = row['classname']\n    image_path = row['img']\n    if not driver_to_img.get(driver, False):\n        driver_to_img[driver] = [image_path]\n    else:\n        driver_to_img.get(driver).append(image_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e86bac1f7ebc27afa8491678e90855ddb320c6c"},"cell_type":"code","source":"# 운전자별 훈련 데이터 예시를 시각화한다\nfor driver in np.unique(driver_list['subject']).tolist():\n    for label in labels:\n        f, ax = plt.subplots(figsize=(12, 10))\n        files = glob('{}/train/{}/*.jpg'.format(data_dir, label))\n        print_files = []\n        for fl in files:\n            if (driver_list[driver_list['img'] == os.path.basename(fl)]['subject'] == driver).values[0]:\n                print_files.append(fl)\n    \n        # 총 9개의 이미지를 시각화한다\n        for x in range(9):\n            plt.subplot(3, 3, x+1)\n            image = read_image(print_files[x])\n            plt.imshow(image)\n            plt.axis('off')\n        plt.show()\n        \n        # 운전자 ID와 클래스를 출력한다\n        print('\\t\\t\\t\\t# 운전자 : {} | 클래스 : \"{} : {}\"'.format(driver, label, col_to_kor[label]))\n    \n    # 첫번째 운전자만 시각화\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0d774ca7b75ca0827f8dcd50f049dff3f94d3d90"},"cell_type":"code","source":"# 훈련 데이터 중 특이한 데이터를 시각화한다\n\ndef plot_images(label, img):\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, label, img))\n    plt.imshow(image)\n    plt.show()\n\n\n# Label : c0 안전 운전\nlabel = 'c0'\nimgs = [21155, 31121]\nprint('# \"c0 : 안전 운전\" Outliers')\nf, ax = plt.subplots(figsize=(12, 10))\nfor x in range(len(imgs)):\n    plt.subplot(1, 2, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, label, imgs[x]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()\n\n\n# Label : c3 왼손으로 문자\nlabel = 'c3'\nimgs = [38563, 45874, 49269, 62784]\nprint('# \"c3: 왼손으로 문자\" Outliers')\nf, ax = plt.subplots(figsize=(12, 10))\nfor x in range(len(imgs)):\n    plt.subplot(2, 2, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, label, imgs[x]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()\n\n\n# Label : c4 왼손으로 전화\nlabel = 'c4'\nimgs = [92769, 38427, 41743, 69998, 77347, 16077]\nprint('# \"c4: 왼손으로 전화\" Outliers')\nf, ax = plt.subplots(figsize=(18, 10))\nfor x in range(len(imgs)):\n    plt.subplot(2, 3, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, label, imgs[x]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()\n\n\n# Label : c9 조수석과 대화\nlabel = 'c9'\nimgs = [28068, 37708, 73663]\nprint('# \"c9: 조수석과 대화\" Outliers')\nf, ax = plt.subplots(figsize=(18, 10))\nfor x in range(len(imgs)):\n    plt.subplot(1, 3, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, label, imgs[x]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"44da146d531a752ed447e85c0e3874d80e4442c6"},"cell_type":"code","source":"# 잘못 분류된 훈련 데이터의 일부를 시각화한다\n\n# Real Label : c0\nimgs = [('c5', 30288), ('c7', 46617), ('c8', 3835)]\nf, ax = plt.subplots(figsize=(18, 10))\nprint('# Examples of c0 : 안전운전 classified in wrong labels')\nfor x in range(len(imgs)):\n    plt.subplot(1, 3, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, imgs[x][0], imgs[x][1]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()\n\n# Real Label : c1\nimgs = [('c0', 29923), ('c0', 79819), ('c2', 32934)]\nf, ax = plt.subplots(figsize=(18, 10))\nprint('# Examples of c1 : 오른손으로 문자 classified in wrong labels')\nfor x in range(len(imgs)):\n    plt.subplot(1, 3, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, imgs[x][0], imgs[x][1]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()\n\n# Real Label : c8\nimgs = [('c0', 34380), ('c3', 423), ('c5', 78504)]\nf, ax = plt.subplots(figsize=(18, 10))\nprint('# Examples of c8 : 얼굴, 머리 만지기 classified in wrong labels')\nfor x in range(len(imgs)):\n    plt.subplot(1, 3, x+1)\n    image = read_image('{}train/{}/img_{}.jpg'.format(data_dir, imgs[x][0], imgs[x][1]))\n    plt.imshow(image)\n    plt.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f540329cb21e3a31850ad093027de58090167dc7"},"cell_type":"code","source":"# 데이터 어그멘테이션 예시\n\n# 이미지 파일 경로를 지정한다\ndata_dir = '../input/'\n# data_dir = '~/.kaggle/competitions/state-farm-distracted-driver-detection/'\nimg_path = [('c0', 55301), ('c5', 92551), ('c8', 71055)]\n\n# 이미지를 그대로 읽어온다\nimgs = []\nfor x in range(len(img_path)):\n    imgs.append(read_image('{}train/{}/img_{}.jpg'.format(data_dir, img_path[x][0], img_path[x][1])) / 255.)\n\n# 이미지를 시각화한다\nf, ax = plt.subplots(figsize=(18, 10))\nfor i, img in enumerate(imgs):\n    plt.subplot(1, 3, i+1)\n    plt.imshow(img)\n    plt.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1d971cd26d8f99ab9d8a21fb8196e530e2dfaf00"},"cell_type":"code","source":"from scipy.ndimage import rotate\n\n# 임의의 회전 각도(rotate_angle)을 구한 후, 이미지를 회전한다.\nrotate_angle = np.random.randint(40) - 20\nprint('# 이미지 회전 : {}도'.format(rotate_angle))\nfor i, img in enumerate(imgs):\n    imgs[i] = rotate(img, rotate_angle)\n    imgs[i] -= np.min(imgs[i])\n    imgs[i] /= np.max(imgs[i])\n\n# 이미지를 시각화한다.\nf, ax = plt.subplots(figsize=(18, 10))\nfor x, img in enumerate(imgs):\n    plt.subplot(1, 3, x+1)\n    plt.imshow(img)\n    plt.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"35a9a17f37d766f87059fb17f4453aaa74a57db0"},"cell_type":"code","source":"def crop_center(img, cropx, cropy):\n    # 이미지 중간을 Crop하는 함수를 정의한다\n    y,x = img.shape\n    startx = x//2-(cropx//2)\n    starty = y//2-(cropy//2)    \n    return img[starty:starty+cropy,startx:startx+cropx]\n\n# x,y 축의 이미지 확대 비율을 랜덤으로 정의한다\nwidth_zoom = int(image.shape[0] * (0.8 + 0.2 * (1 - np.random.random())))\nheight_zoom = int(image.shape[1] * (0.8 + 0.2 * (1 - np.random.random())))\n\n# 이미지를 확대한다\nprint('# 이미지 줌 인 : (x : {}, y : {})'.format(round(1. * width_zoom / image.shape[0], 2), \\\n                                            round(1. *height_zoom / image.shape[1],2 )))\nfor i, img in enumerate(imgs):\n    final_image = np.zeros((width_zoom, height_zoom, 3))\n    final_image[:,:,0] = crop_center(img[:,:,0], height_zoom, width_zoom)\n    final_image[:,:,1] = crop_center(img[:,:,1], height_zoom, width_zoom)\n    final_image[:,:,2] = crop_center(img[:,:,2], height_zoom, width_zoom)\n    imgs[i] = final_image\n\n# 이미지를 시각화한다\nf, ax = plt.subplots(figsize=(18, 10))\nfor x, img in enumerate(imgs):\n    plt.subplot(1, 3, x+1)\n    plt.imshow(img)\n    plt.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a8cfed017be0fc2301f68388501983e79eec1356"},"cell_type":"code","source":"# 10x10 크기의 커널로 이미지를 흐린다\nblur_degree = 10\nprint('{}x{} 커널 크기로 이미지 흐리기'.format(blur_degree, blur_degree))\nfor i, img in enumerate(imgs):\n    imgs[i] = cv2.blur(img,(blur_degree,blur_degree))\n\n# 이미지를 시각화한다\nf, ax = plt.subplots(figsize=(18, 10))\nfor x, img in enumerate(imgs):\n    plt.subplot(1, 3, x+1)\n    plt.imshow(img)\n    plt.axis('off')\nplt.show()","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}