{"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_minor":4,"nbformat":4,"cells":[{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kaggle competitions download -c counting-and-categorizing-vehicles-in-surveillance\n","metadata":{"execution":{"iopub.status.busy":"2023-02-03T01:20:43.266353Z","iopub.execute_input":"2023-02-03T01:20:43.267342Z","iopub.status.idle":"2023-02-03T01:20:43.298322Z","shell.execute_reply.started":"2023-02-03T01:20:43.267218Z","shell.execute_reply":"2023-02-03T01:20:43.296730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import xml.etree.ElementTree as ET\nimport os\nimport pandas as pd\n\n# 폴더 경로\nfolder_path = '/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/train/xml'\n\ndf = pd.DataFrame(columns=['filename', 'name', 'xmin', 'ymin', 'xmax', 'ymax'])\n\n# 폴더에 있는 xml 파일들을 파싱\nfor filename in os.listdir(folder_path):\n    if filename.endswith('.xml'):\n        # xml 파일을 열고 파싱\n        file = filename.replace('.xml', '.jpg') # filename에서 '.xml'을 '.jpg'로 변경\n        tree = ET.parse(os.path.join(folder_path, filename))\n        root = tree.getroot()\n        \n        for obj in root.iter('object'):\n            name = obj.find('name').text\n            bndbox = obj.find('bndbox')\n            xmin = bndbox.find('xmin').text\n            ymin = bndbox.find('ymin').text\n            xmax = bndbox.find('xmax').text\n            ymax = bndbox.find('ymax').text\n            \n            df = df.append({'filename': file, # '.xml' 변경한 filename 사용\n                            'name': name,\n                            'xmin': xmin,\n                            'ymin': ymin,\n                            'xmax': xmax,\n                            'ymax': ymax}, ignore_index=True)\n\nprint(df)","metadata":{"execution":{"iopub.status.busy":"2023-02-03T04:06:00.684039Z","iopub.execute_input":"2023-02-03T04:06:00.684814Z","iopub.status.idle":"2023-02-03T04:06:18.292594Z","shell.execute_reply.started":"2023-02-03T04:06:00.684766Z","shell.execute_reply":"2023-02-03T04:06:18.291801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip uninstall --yes opencv-contrib-python opencv-python\n!pip install opencv-contrib-python","metadata":{"execution":{"iopub.status.busy":"2023-02-03T02:45:50.308948Z","iopub.execute_input":"2023-02-03T02:45:50.309885Z","iopub.status.idle":"2023-02-03T02:46:15.648541Z","shell.execute_reply.started":"2023-02-03T02:45:50.309769Z","shell.execute_reply":"2023-02-03T02:46:15.647197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport os\nimport random\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2023-02-03T04:00:50.861308Z","iopub.execute_input":"2023-02-03T04:00:50.862147Z","iopub.status.idle":"2023-02-03T04:00:57.155778Z","shell.execute_reply.started":"2023-02-03T04:00:50.862108Z","shell.execute_reply":"2023-02-03T04:00:57.154484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Image(Train):',len(os.listdir('/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/train/jpg')))\nprint('Image(Test):',len(os.listdir('/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/test/jpg')))","metadata":{"execution":{"iopub.status.busy":"2023-02-03T04:00:58.779945Z","iopub.execute_input":"2023-02-03T04:00:58.781526Z","iopub.status.idle":"2023-02-03T04:00:59.020062Z","shell.execute_reply.started":"2023-02-03T04:00:58.781471Z","shell.execute_reply":"2023-02-03T04:00:59.018789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport xml.etree.ElementTree as ET\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D\nfrom tensorflow.keras.models import Model\n\n# Define the path to the training images and annotations\ntrain_img_path = '/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/train/jpg'\ntrain_annot_path = '/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/train/xml'\n\n# Load the training images and annotations\ntrain_imgs = []\ntrain_annotations = []\nfor img_file in os.listdir(train_img_path):\n    img = cv2.imread(os.path.join(train_img_path, img_file))\n    train_imgs.append(img)\n    annot_file = os.path.splitext(img_file)[0] + '.xml'\n    annot_tree = ET.parse(os.path.join(train_annot_path, annot_file))\n    annot_root = annot_tree.getroot()\n    annot = []\n    for object_ in annot_root.iter('object'):\n        name = object_.find('name').text\n        xmin = int(object_.find('bndbox/xmin').text)\n        ymin = int(object_.find('bndbox/ymin').text)\n        xmax = int(object_.find('bndbox/xmax').text)\n        ymax = int(object_.find('bndbox/ymax').text)\n        annot.append([xmin, ymin, xmax, ymax, name])\n    train_annotations.append(annot)\n    \n# Preprocess the training data\ntrain_imgs = np.array(train_imgs) / 255.\ntrain_annotations = np.array(train_annotations)\n\n# Build the object detection model using YOLO\ninput_img = Input(shape=(None, None, 3))\n\n# Add the YOLO layers to the model\n# ...\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy')\n\n# Train the model\nmodel.fit(train_imgs, train_annotations, epochs=10, batch_size=32)\n\n# Save the model\nmodel.save('trained_model.h5')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()\n","metadata":{"execution":{"iopub.status.busy":"2023-02-03T04:01:06.994571Z","iopub.execute_input":"2023-02-03T04:01:06.994992Z","iopub.status.idle":"2023-02-03T04:01:07.012503Z","shell.execute_reply.started":"2023-02-03T04:01:06.994959Z","shell.execute_reply":"2023-02-03T04:01:07.011568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in df.values:\n  photo=plt.imread(f'/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/train/jpg/{i[0]}')\n  plt.imshow(photo)\n  print('Photo shape:',photo.shape)\n  print('file,name,xmin,ymin,xmax,ymax:',i)\n  pt1=(int(i[2]),int(i[3]))\n  pt2=(int(i[4]),int(i[5]))\n  color=(255, 0, 0)\n  thickness = 2\n  cv2.rectangle(photo,pt1,pt2, color, thickness)\n  plt.figure()\n  plt.imshow(photo)\n  break","metadata":{"execution":{"iopub.status.busy":"2023-02-03T04:10:30.533512Z","iopub.execute_input":"2023-02-03T04:10:30.533955Z","iopub.status.idle":"2023-02-03T04:10:31.488036Z","shell.execute_reply.started":"2023-02-03T04:10:30.533921Z","shell.execute_reply":"2023-02-03T04:10:31.487012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in df.values:\n    photo = plt.imread(f'/kaggle/input/counting-and-categorizing-vehicles-in-surveillance/train/jpg/{i[0]}')\n    plt.imshow(photo)\n    print('Photo shape:', photo.shape)\n    print('name, xmin, ymin, xmax, ymax:', i)\n    for j in range(len(df.index)):\n        if i[0] == df.iloc[j][0]:\n            pt1 = (int(df.iloc[j][2]), int(df.iloc[j][3]))\n            pt2 = (int(df.iloc[j][4]), int(df.iloc[j][5]))\n            color = (255, 0, 0)\n            thickness = 2\n            cv2.rectangle(photo, pt1, pt2, color, thickness)\n    plt.figure()\n    plt.imshow(photo)\n    break","metadata":{"execution":{"iopub.status.busy":"2023-02-03T04:11:21.931218Z","iopub.execute_input":"2023-02-03T04:11:21.931709Z","iopub.status.idle":"2023-02-03T04:11:23.407153Z","shell.execute_reply.started":"2023-02-03T04:11:21.931670Z","shell.execute_reply":"2023-02-03T04:11:23.406020Z"},"trusted":true},"execution_count":null,"outputs":[]}]}