{"cells":[{"metadata":{},"cell_type":"markdown","source":"Wheat Detection EDA","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"https://www.kaggle.com/devvindan/wheat-detection-eda","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"파일","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"sample_submission.csv","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"test","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"train","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"train.csv","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nfrom PIL import Image, ImageDraw\nfrom ast import literal_eval\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**데이터 로드**","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"root_path = \"../Wheat/\"\ntrain_folder = os.path.join(root_path, \"train\")\ntest_folder = os.path.join(root_path, \"test\")\ntrain_csv_path = os.path.join(root_path, \"train.csv\")\nsample_submission = os.path.join(root_path, \"sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"df = pd.read_csv(train_csv_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"#.head() 함수를 이용하여 상위 5행을 출력\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"#index 0번째의 데이터 개수\ndf.shape[0]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**몇 가지 기초 통계**","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"모든 이미지의 해상도는 1024 x 1024 이다.","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"#.unique() 개별 컬럼 내에 유일한 값을 확인, 해상도가 1024인지 확인\n#width와 height가 1024이므로 결과 값 ture\ndf['width'].unique() == df['height'].unique() == [1024]","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"def get_bbox_area(bbox):\n    bbox = literal_eval(bbox)\n    return bbox[2] * bbox[3]","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"df['bbox_area'] = df['bbox'].apply(get_bbox_area)","execution_count":null,"outputs":[]},{"metadata":{"scrolled":true,"trusted":false},"cell_type":"code","source":"#bbox index 2 * index 3\ndf['bbox_area']","execution_count":null,"outputs":[]},{"metadata":{"scrolled":false,"trusted":false},"cell_type":"code","source":"#bbox index 2 * index 3의 개수 count\ndf['bbox_area'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"scrolled":true,"trusted":false},"cell_type":"code","source":"df['bbox_area'].value_counts().hist(bins=30)\nplt.xlabel('number of bboxes')\nplt.ylabel('area')\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"면적이 클수록 bbox의 개수가 작아지고, 면적이 작을수록 bbox의 개수가 커진다.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"이미지마다 바운드 박스가 많이 있으며, 모든 이미지가 밀 머리와 바운드 박스를 포함하지는 않는다.","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"unique_images = df['image_id'].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"num_total = len(os.listdir(train_folder))\nnum_annotated = len(unique_images)\n\nprint(f\"There are {num_annotated} annotated images and {num_total - num_annotated} images without annotations.\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"주석 처리된 영상은 3373개, 주석이 없는 영상은 49개이다. (주석 처리 = 바운드 박스)","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"**데이터 출처**","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"sources = df['source'].unique()\nprint(f\"There are {len(sources)} sources of data: {sources}\")","execution_count":null,"outputs":[]},{"metadata":{"scrolled":true,"trusted":false},"cell_type":"code","source":"df['source'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**각 이미지마다 몇 개의 바운드 박스가 있는지 살펴보기**","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"plt.hist(df['image_id'].value_counts(), bins=30)\nplt.xlabel('number of bboxes')\nplt.ylabel('number of images')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"train.csv에서의 바운드 박수 수 ","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"각 이미지마다 최대 바운드 박스 수는 116개, 최소 바운드 박스 수는 1개이다.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"**이미지 시각화**","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"def show_images(images, num = 5):\n    \n    images_to_show = np.random.choice(images, num)\n\n    for image_id in images_to_show:\n\n        image_path = os.path.join(train_folder, image_id + \".jpg\")\n        image = Image.open(image_path)\n\n        # get all bboxes for given image in [xmin, ymin, width, height]\n        bboxes = [literal_eval(box) for box in df[df['image_id'] == image_id]['bbox']]\n\n        # visualize them\n        draw = ImageDraw.Draw(image)\n        for bbox in bboxes:    \n            draw.rectangle([bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]], width=3)\n\n        plt.figure(figsize = (15,15))\n        plt.imshow(image)\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"show_images(unique_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"6. 출처별 사진 보기","execution_count":null},{"metadata":{"trusted":false},"cell_type":"code","source":"for source in sources:\n    print(f\"Showing images for {source}:\")\n    show_images(df[df['source'] == source]['image_id'].unique(), num = 3)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**시각화를 통해 알 수 있는 내용**","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"* 중복된 바운드 박스가 많다.\n* 사진을 수직으로 찍은 것처럼 보인다.\n* 모든 식물은 다르게 회전할 수 있고, 단일한 방향은 없다.(자라는 방향이 일정하지 않다.) 이것은 flip(그림 좌우 및 상하 반전시키기)의 사용이 도움이 될 수 있다.\n* 밀 머리 색은 모두 다르며 근원(source)에 좌우되는 것 같다.\n* 밀 머리 자체는 관찰자와 관련된 매우 다른 각도에서 볼 수 있다.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"<정리>","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"* 모든 이미지의 해상도는 1024 x 1024\n* bbox의 면적이 클수록 bbox의 개수가 작아지고, 면적이 작을수록 bbox의 개수가 커짐\n* 이미지마다 bbox가 많이 있지만, 모든 이미지가 bbox를 포함하진 않음\n* bbox가 있는 이미지는 3373개, bbox가 없는 이미지는 49개임 (bbox는 곧 밀의 머리)\n* train.csv에서의 각 이미지마다 최대 bbox 수는 116개, 최소 bbox 수는 1개임\n* 중복되는 bbox가 많았음","execution_count":null}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}