{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"},{"sourceId":139474,"sourceType":"modelInstanceVersion","modelInstanceId":118113,"modelId":141350},{"sourceId":205304,"sourceType":"modelInstanceVersion","modelInstanceId":175078,"modelId":197440},{"sourceId":205595,"sourceType":"modelInstanceVersion","modelInstanceId":175336,"modelId":197686},{"sourceId":205873,"sourceType":"modelInstanceVersion","modelInstanceId":175589,"modelId":197940},{"sourceId":207212,"sourceType":"modelInstanceVersion","modelInstanceId":176661,"modelId":198971}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\n!pip install ultralytics --no-index --find-links=file:///kaggle/input/ceshibixuku/pytorch/default/1\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-23T01:08:28.904488Z","iopub.execute_input":"2024-12-23T01:08:28.905310Z","iopub.status.idle":"2024-12-23T01:08:38.113713Z","shell.execute_reply.started":"2024-12-23T01:08:28.905267Z","shell.execute_reply":"2024-12-23T01:08:38.112626Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport os\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nfrom pathlib import Path\nfrom tqdm import tqdm\nfrom ultralytics import YOLO\n\n# Constants\nROOT_PATH = '/kaggle/input/global-wheat-detection'\nIMG_SIZE = 416  # Model input size\n\ndef load_test_image(image_id):\n    \"\"\"Load and preprocess test image\"\"\"\n    img_path = os.path.join(ROOT_PATH, 'test', f'{image_id}.jpg')\n    img = Image.open(img_path)\n    original_size = img.size  # 保存原始尺寸\n    # 调整到模型输入尺寸\n    img = img.resize((IMG_SIZE, IMG_SIZE))\n    return np.asarray(img), original_size\n\ndef convert_yolo_to_submission(predictions, image_id, original_size):\n    \"\"\"Convert YOLO predictions to submission format\n    \n    Format: image_id,confidence x y width height [confidence x y width height ...]\n    Example: ce4833752,0.5 0 0 100 100\n    Multiple boxes: 1da9078c1,0.3 0 0 50 50 0.5 10 10 30 30\n    Empty prediction: 6ca7b2650,\n    \"\"\"\n    if len(predictions) == 0:\n        return f\"{image_id},\"\n    \n    original_width, original_height = original_size\n    boxes = []\n    \n    for pred in predictions:\n        # 获取置信度\n        conf = pred.conf.item()\n        \n        # 获取归一化的边界框坐标（xywh格式）\n        x_center, y_center, width, height = pred.xywh[0][:4].tolist()\n        \n        # 转换为原始图像像素坐标（左上角格式）\n        x = max(0, int((x_center - width/2) * original_width))\n        y = max(0, int((y_center - height/2) * original_height))\n        w = int(width * original_width)\n        h = int(height * original_height)\n        \n        # 格式化为整数坐标\n        boxes.append(f\"{conf:.1f} {x} {y} {w} {h}\")\n    \n    return f\"{image_id},{' '.join(boxes)}\"\n\ndef predict_test_dataset(model_path, confidence_threshold=0.3):\n    \"\"\"Generate predictions for test dataset\"\"\"\n    # 加载模型\n    model = YOLO(model_path)\n    \n    # 获取测试图像ID列表\n    test_images = [f.stem for f in Path(os.path.join(ROOT_PATH, 'test')).glob('*.jpg')]\n    \n    # 生成预测结果\n    submission_rows = []\n    for image_id in tqdm(test_images, desc='Predicting'):\n        # 加载和预处理图像\n        img, original_size = load_test_image(image_id)\n        \n        # 预测\n        results = model.predict(\n            source=img,\n            conf=confidence_threshold,\n            imgsz=IMG_SIZE,  # 使用相同的输入尺寸\n            verbose=False\n        )\n        \n        # 转换预测结果为提交格式\n        submission_row = convert_yolo_to_submission(results[0].boxes, image_id, original_size)\n        submission_rows.append(submission_row)\n    \n    # 创建提交DataFrame\n    submission_df = pd.DataFrame(\n        [row.split(',') for row in submission_rows], \n        columns=['image_id', 'PredictionString']\n    )\n    \n    return submission_df\n\ndef main():\n    # 模型权重路径\n    model_path = '/kaggle/input/ceshi1/pytorch/default/1/best (2).pt'\n    \n    # 生成预测结果\n    print(\"Generating predictions...\")\n    submission_df = predict_test_dataset(\n        model_path=model_path,\n        confidence_threshold=0.3  # 根据验证结果调整此阈值\n    )\n    \n    # 保存提交文件\n    submission_path = '/kaggle/working/submission.csv'\n    submission_df.to_csv(submission_path, index=False)\n    print(f\"Submission saved to {submission_path}\")\n\nif __name__ == \"__main__\":\n    main()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-23T00:42:26.724755Z","iopub.execute_input":"2024-12-23T00:42:26.725739Z","iopub.status.idle":"2024-12-23T00:44:05.737947Z","shell.execute_reply.started":"2024-12-23T00:42:26.725699Z","shell.execute_reply":"2024-12-23T00:44:05.736980Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-23T00:45:10.441772Z","iopub.execute_input":"2024-12-23T00:45:10.442608Z","iopub.status.idle":"2024-12-23T00:45:10.448010Z","shell.execute_reply.started":"2024-12-23T00:45:10.442567Z","shell.execute_reply":"2024-12-23T00:45:10.447168Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-23T00:23:51.748671Z","iopub.execute_input":"2024-12-23T00:23:51.748958Z","iopub.status.idle":"2024-12-23T00:24:08.145352Z","shell.execute_reply.started":"2024-12-23T00:23:51.748919Z","shell.execute_reply":"2024-12-23T00:24:08.144632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-23T00:24:08.146607Z","iopub.execute_input":"2024-12-23T00:24:08.147120Z","iopub.status.idle":"2024-12-23T00:24:11.156361Z","shell.execute_reply.started":"2024-12-23T00:24:08.147082Z","shell.execute_reply":"2024-12-23T00:24:11.155513Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}