{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":75079,"databundleVersionId":8238839,"sourceType":"competition"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":{"iopub.status.busy":"2025-07-08T11:46:04.461279Z","iopub.execute_input":"2025-07-08T11:46:04.461444Z","iopub.status.idle":"2025-07-08T11:46:06.081600Z","shell.execute_reply.started":"2025-07-08T11:46:04.461430Z","shell.execute_reply":"2025-07-08T11:46:06.080988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install ultralytics supervision -q","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:46:06.082260Z","iopub.execute_input":"2025-07-08T11:46:06.082675Z","iopub.status.idle":"2025-07-08T11:47:22.851484Z","shell.execute_reply.started":"2025-07-08T11:46:06.082640Z","shell.execute_reply":"2025-07-08T11:47:22.850691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport pandas as pd\nimport numpy as np\nfrom ultralytics import YOLO\nimport supervision as sv\nfrom tqdm import tqdm\nimport zipfile","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:47:22.852837Z","iopub.execute_input":"2025-07-08T11:47:22.853129Z","iopub.status.idle":"2025-07-08T11:47:27.089328Z","shell.execute_reply.started":"2025-07-08T11:47:22.853094Z","shell.execute_reply":"2025-07-08T11:47:27.088545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"OUTPUT_PATH = \"/kaggle/working\"\nMODEL_NAME = \"yolov8x.pt\"\nCONFIDENCE_THRESHOLD = 0.3","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:47:27.090153Z","iopub.execute_input":"2025-07-08T11:47:27.090500Z","iopub.status.idle":"2025-07-08T11:47:27.094239Z","shell.execute_reply.started":"2025-07-08T11:47:27.090480Z","shell.execute_reply":"2025-07-08T11:47:27.093526Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.makedirs(f\"{OUTPUT_PATH}/train/images\", exist_ok=True)\nos.makedirs(f\"{OUTPUT_PATH}/train/labels\", exist_ok=True)\nos.makedirs(f\"{OUTPUT_PATH}/test/images\", exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:47:27.099878Z","iopub.execute_input":"2025-07-08T11:47:27.100345Z","iopub.status.idle":"2025-07-08T11:47:27.114963Z","shell.execute_reply.started":"2025-07-08T11:47:27.100320Z","shell.execute_reply":"2025-07-08T11:47:27.114466Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def prepare_yolo_dataset():\n    yaml_content = f\"\"\"path: /kaggle/input/cars-object-detection/train/train\ntrain: /kaggle/input/cars-object-detection/train/train/images\nval: /kaggle/input/cars-object-detection/train/train/images\nnc: 1\nnames: ['car']\n\"\"\"\n    with open(f\"{OUTPUT_PATH}/data.yaml\", \"w\") as f:\n        f.write(yaml_content)\n    print(\"\\nСодержимое data.yaml:\")\n    with open(f\"{OUTPUT_PATH}/data.yaml\", \"r\") as f:\n        print(f.read())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:47:43.367425Z","iopub.execute_input":"2025-07-08T11:47:43.368055Z","iopub.status.idle":"2025-07-08T11:47:43.372351Z","shell.execute_reply.started":"2025-07-08T11:47:43.368004Z","shell.execute_reply":"2025-07-08T11:47:43.371621Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"prepare_yolo_dataset()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:48:34.947814Z","iopub.execute_input":"2025-07-08T11:48:34.948111Z","iopub.status.idle":"2025-07-08T11:48:34.952788Z","shell.execute_reply.started":"2025-07-08T11:48:34.948088Z","shell.execute_reply":"2025-07-08T11:48:34.952204Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_model():\n    model = YOLO(MODEL_NAME)\n    \n    # Гиперпараметры с аугментациями\n    results = model.train(\n        data=f\"{OUTPUT_PATH}/data.yaml\",\n        epochs=50,\n        batch=16,\n        imgsz=640,\n        device=0,\n        patience=10,\n        verbose=True,\n        # Дополнительные аугментации\n        hsv_h=0.015,\n        hsv_s=0.7,\n        hsv_v=0.4,\n        degrees=10.0,\n        translate=0.1,\n        scale=0.5,\n        shear=0.0,\n        perspective=0.0001,\n        fliplr=0.5,\n        mosaic=1.0,\n        mixup=0.1,\n        copy_paste=0.0,\n        close_mosaic=10,  # Отключить мозаику последние 10 эпох\n        overlap_mask=True,\n        single_cls=True   # Только один класс\n    )\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:49:14.926260Z","iopub.execute_input":"2025-07-08T11:49:14.926768Z","iopub.status.idle":"2025-07-08T11:49:14.931824Z","shell.execute_reply.started":"2025-07-08T11:49:14.926743Z","shell.execute_reply":"2025-07-08T11:49:14.931163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = train_model()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T11:49:26.538366Z","iopub.execute_input":"2025-07-08T11:49:26.538883Z","iopub.status.idle":"2025-07-08T12:16:05.222348Z","shell.execute_reply.started":"2025-07-08T11:49:26.538857Z","shell.execute_reply":"2025-07-08T12:16:05.221346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def generate_predictions(model):\n    test_images_path = \"/kaggle/input/cars-object-detection/test/test/images\"\n    test_images = [f for f in os.listdir(test_images_path) if f.endswith('.JPG')]\n    predictions = []\n    \n    for image_file in tqdm(test_images, desc=\"Обработка тестовых изображений\"):\n        image_path = f\"{test_images_path}/{image_file}\"\n        image = cv2.imread(image_path)\n        \n        results = model.predict(image, conf=CONFIDENCE_THRESHOLD, verbose=False)[0]\n        detections = sv.Detections.from_ultralytics(results)\n        \n        preds = []\n        for detection in detections:\n            # Новый способ распаковки для YOLOv8\n            bbox = detection[0]  # [x1, y1, x2, y2]\n            confidence = detection[2]  # confidence score\n            class_id = detection[3]  # class ID\n            \n            x1, y1, x2, y2 = bbox\n            width = x2 - x1\n            height = y2 - y1\n            center_x = (x1 + width/2) / image.shape[1]\n            center_y = (y1 + height/2) / image.shape[0]\n            width /= image.shape[1]\n            height /= image.shape[0]\n            \n            preds.extend([0, float(confidence), float(center_x), float(center_y), float(width), float(height)])\n        \n        image_id = os.path.splitext(image_file)[0]\n        predictions.append({\n            \"id\": image_id,\n            \"predictions\": f\"[{','.join(map(str, preds))}]\" if preds else \"[]\"\n        })\n    \n    submission_df = pd.DataFrame(predictions)\n    submission_df.to_csv(f\"{OUTPUT_PATH}/submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T13:29:43.574866Z","iopub.execute_input":"2025-07-08T13:29:43.575487Z","iopub.status.idle":"2025-07-08T13:29:43.582533Z","shell.execute_reply.started":"2025-07-08T13:29:43.575461Z","shell.execute_reply":"2025-07-08T13:29:43.581788Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"generate_predictions(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-08T13:29:47.024211Z","iopub.execute_input":"2025-07-08T13:29:47.024495Z","iopub.status.idle":"2025-07-08T13:29:54.048544Z","shell.execute_reply.started":"2025-07-08T13:29:47.024473Z","shell.execute_reply":"2025-07-08T13:29:54.047720Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}