{"id":47754194,"url":"https://github.com/json031/yolo_inspection_kit","last_synced_at":"2026-04-06T07:01:09.694Z","repository":{"id":348294259,"uuid":"1196796736","full_name":"Json031/yolo_inspection_kit","owner":"Json031","description":"基于 YOLOv8 构建的轻量级 YOLO 检测工具包，用于产品包装验证和质量检测。A lightweight YOLO-based detection toolkit for product packaging verification and quality inspection, built on YOLOv8.","archived":false,"fork":false,"pushed_at":"2026-04-01T05:40:19.000Z","size":439,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-03T11:42:46.624Z","etag":null,"topics":["computer-vision","cv","object-detection","opencv","packaging-inspection","python","roi","yolo","yolov8"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Json031.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-31T03:41:50.000Z","updated_at":"2026-04-01T05:40:23.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/Json031/yolo_inspection_kit","commit_stats":null,"previous_names":["json031/yolo_inspection_kit"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/Json031/yolo_inspection_kit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Json031%2Fyolo_inspection_kit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Json031%2Fyolo_inspection_kit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Json031%2Fyolo_inspection_kit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Json031%2Fyolo_inspection_kit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Json031","download_url":"https://codeload.github.com/Json031/yolo_inspection_kit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Json031%2Fyolo_inspection_kit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31388169,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T04:26:24.776Z","status":"ssl_error","status_checked_at":"2026-04-04T04:23:34.147Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["computer-vision","cv","object-detection","opencv","packaging-inspection","python","roi","yolo","yolov8"],"created_at":"2026-04-03T04:01:03.350Z","updated_at":"2026-04-04T05:01:15.655Z","avatar_url":"https://github.com/Json031.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"[中文](README_CN.md) | English\n\n# YOLO Inspection Kit (yolo_inspection_kit)\n\nA lightweight YOLO-based detection toolkit for product packaging verification and quality inspection, built on YOLOv8.\n\n## 📋 Table of Contents\n- [Features](#features)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Configuration](#configuration)\n- [Usage Examples](#usage-examples)\n- [API Documentation](#api-documentation)\n- [FAQ](#faq)\n\n## ✨ Features\n\n- 🎯 **Full Image Detection** - Single-pass YOLO detection on entire image\n- 🔍 **Multi-ROI Detection** - Divide image into regions and detect independently\n- 📊 **Smart Analysis** - Automatically analyze results and identify missing/excess items\n- ⚙️ **Flexible Configuration** - Support code parameters, config files, and environment variables\n- 🖼️ **Visualization** - Generate images with detection boxes\n- 🚀 **Easy Integration** - Simple API to get started in one line\n![纯脚本检测结果](./docs/dec_results/detection_results.jpg)\n![包装清单检测成功示例](./docs/dec_results/packages_detection_results_succ.jpg)\n![包装清单检测失败示例](./docs/dec_results/packages_detection_results_fail.jpg)\n\n## 📦 Installation\n\n### Basic Installation\n\n```bash\npip install yolo_inspection_kit\n```\n\n### Full Installation (with all dependencies)\n\n```bash\npip install yolo_inspection_kit[all]\n```\n\n### Install from Source\n\n```bash\ngit clone https://github.com/Json031/yolo_inspection_kit.git\ncd yolo_inspection_kit\npip install -e .\n```\n\n## 🚀 Quick Start\n\n### Four Configuration Methods\n\n#### Method 1️⃣: Code Parameters (Recommended) ✨\n```python\nfrom yolo_inspection_kit import YoloInspector\n\n# No config file needed - configure directly with parameters\ninspector = YoloInspector(\n    model_path='./models/best.pt',\n    save_dir='./detection_results',\n    expected_counts={\n        'huasa1': 1,\n        'shuilongtou1': 1,\n        'jiaofa1': 1,\n    },\n    confidence_threshold=0.6\n)\n\n# Detect image\nresult = inspector.inspect_image('test_image.jpg')\nprint(f\"Detection Status: {result['analysis']['status']}\")\n```\n\n#### Method 2️⃣: Config File (Backward Compatible)\n```bash\n# 1. Copy config file\ncp config/default_config.yaml config/my_config.yaml\n```\n\nEdit parameters in `config/my_config.yaml`:\n```yaml\nmodel_path: \"./models/best.pt\"\nexpected_counts:\n  huasa1: 1\n  shuilongtou1: 1\n```\n\nUse in Python:\n```python\nfrom yolo_inspection_kit import YoloInspector\n\ninspector = YoloInspector('config/my_config.yaml')\nresult = inspector.inspect_image('test_image.jpg')\n```\n\n#### Method 3️⃣: Hybrid (Config File + Code Parameters)\n```python\n# Load config file but override with code parameters\ninspector = YoloInspector(\n    'config/default_config.yaml',\n    model_path='./models/custom_best.pt',  # Override\n    confidence_threshold=0.75               # Override\n)\nresult = inspector.inspect_image('test_image.jpg')\n```\n\n#### Method 4️⃣: Environment Variables (Production Recommended)\n```bash\n# Set environment variables\nexport YOLO_MODEL_PATH=\"./models/best.pt\"\nexport YOLO_SAVE_DIR=\"./detection_results\"\n\n# Python code\ninspector = YoloInspector(\n    expected_counts={'huasa1': 1, 'shuilongtou1': 1}\n)\n```\n\n### Configuration Priority\n```\nCode Parameters \u003e Environment Variables \u003e Config File \u003e Default Values\n```\n\n## ⚙️ Configuration\n\n### Config File Structure\n\nAll parameters are managed in YAML format. Reference `config/default_config.yaml`\n\n### Key Configuration Parameters\n\n#### 1. Model Configuration\n\n```yaml\n# Path to trained YOLO model (required)\n# Supports: relative path, absolute path, ~ for home directory\n# Must be .pt format (PyTorch weights)\nmodel_path: \"./models/best.pt\"\n\n# Confidence threshold for YOLO predictions (0-1)\n# Detections below this are discarded\nmodel_predict_conf: 0.8\n\n# Confidence threshold for results filtering (0-1)\n# Additional filtering of low-confidence detections\nconfidence_threshold: 0.6\n```\n\n**How to get model path:**\n```bash\n# Model is usually saved at\nruns/detect/train/weights/best.pt\n\n# Copy to project directory\ncp runs/detect/train/weights/best.pt ./models/\n```\n\n#### 2. Save Configuration\n\n```yaml\n# Directory to save detection results (required)\n# Creates directory if it doesn't exist\nsave_dir: \"./detection_results\"\n\n# Enable audio alerts\naudio_alerts_enabled: false\n```\n\n#### 3. Expected Counts Configuration (Required)\n\nCritical configuration for determining pass/fail status.\n\n```yaml\nexpected_counts:\n  huasa1: 1           # Expect 1 huasa\n  jiaofa1: 1          # Expect 1 jiaofa\n  shuilongtou1: 1     # Expect 1 shuilongtou\n  linyuguan1: 1       # Expect 1 linyuguan\n  ruanguan1: 1        # Expect 1 ruanguan\n  shengliaodai1: 1    # Expect 1 shengliaodai\n```\n\n**Key Points:**\n- `key` must exactly match model's class_name\n- `value` is expected count for that class\n- If actual \u003c expected: \"Missing\"\n- If actual \u003e expected: \"Excess\"\n- If actual = expected: \"✅\"\n\n**How to get model's class_name?**\n```python\nfrom ultralytics import YOLO\nmodel = YOLO('models/best.pt')\nprint(model.names)  # Output: {0: 'huasa1', 1: 'jiaofa1', ...}\n```\n\n#### 4. ROI Multi-Region Detection Configuration (Optional)\n\nCan be omitted if only full image detection is needed.\n\n```yaml\nroi_definitions:\n  - name: \"Region 1\"\n    x: 0.05          # Top-left X coordinate (relative 0-1)\n    y: 0.05          # Top-left Y coordinate (relative 0-1)\n    w: 0.28          # Width (relative 0-1)\n    h: 0.52          # Height (relative 0-1)\n  \n  - name: \"Region 2\"\n    x: 0.33\n    y: 0.15\n    w: 0.28\n    h: 0.32\n\nroi_colors:\n  - [0, 255, 0]      # BGR format, color for first ROI\n  - [0, 0, 255]      # Color for second ROI\n  - [255, 0, 0]      # ...\n```\n\n**ROI Coordinates Explanation:**\n- x, y, w, h are relative coordinates (0-1)\n- Independent of image resolution, auto-scales\n- Example: `x=0.05, y=0.05, w=0.28, h=0.52` means:\n  - Start from 5% of image width\n  - Start from 5% of image height\n  - ROI width is 28% of image width\n  - ROI height is 52% of image height\n\n**ROI Colors (BGR format):**\n```\nBGR Value      Description\n[0, 255, 0]    Green\n[0, 0, 255]    Red\n[255, 0, 0]    Blue\n[255, 255, 0]  Cyan\n[0, 255, 255]  Yellow\n[255, 0, 255]  Magenta\n```\n\n## 📚 Usage Examples\n\n### Example 1: Simple Full Image Detection (Code Parameters)\n\n```python\nfrom yolo_inspection_kit import YoloInspector\n\n# Initialize with code parameters (recommended)\ninspector = YoloInspector(\n    model_path='./models/best.pt',\n    expected_counts={'product': 10}\n)\n\n# Detect image\nresult = inspector.inspect_image('image.jpg', detection_mode='full')\nprint(result['analysis']['summary'])\n```\n\n### Example 2: Simple Full Image Detection (Config File)\n\n```python\nfrom yolo_inspection_kit import YoloInspector\n\n# Use config file\ninspector = YoloInspector('config/default_config.yaml')\nresult = inspector.inspect_image('image.jpg', detection_mode='full')\n\n# View results\nprint(result['analysis']['summary'])\n```\n\n### Example 3: Multi-ROI Detection\n\n```python\n# Use ROI mode\nresult = inspector.inspect_image('image.jpg', detection_mode='roi')\n\n# View detections in each ROI\nfor roi_info in result['roi_details']:\n    print(f\"{roi_info['name']}: {roi_info['detections']}\")\n```\n\n### Example 4: Batch Processing Images\n\n```python\nimport os\n\nimage_dir = 'test_images'\nfor filename in os.listdir(image_dir):\n    if filename.endswith(('.jpg', '.png')):\n        image_path = os.path.join(image_dir, filename)\n        result = inspector.inspect_image(image_path)\n        \n        if result['analysis']['status'] == 'PASS':\n            print(f\"✓ {filename} passed\")\n        else:\n            print(f\"✗ {filename} failed\")\n            print(result['analysis']['summary'])\n        \n        # Save result image\n        inspector.save_result_image(\n            result['annotated_image'],\n            result['filename']\n        )\n```\n\n### Example 5: Get Model Information\n\n```python\ninfo = inspector.get_model_info()\nprint(f\"Model: {info['model_name']}\")\nprint(f\"Number of classes: {info['num_classes']}\")\nprint(\"All classes:\")\nfor class_id, class_name in info['class_names'].items():\n    print(f\"  {class_id}: {class_name}\")\n```\n\n## 📖 API Documentation\n\n### YoloInspector\n\n```python\nclass YoloInspector:\n    def __init__(self, config_file: Optional[str] = None, **kwargs)\n        \"\"\"Initialize detector\n        \n        Args:\n            config_file: Path to config file (.yaml or .json), optional\n            **kwargs: Code parameters that override config file values\n            \n        Examples:\n            # Method 1: Config file only\n            inspector = YoloInspector('config/default_config.yaml')\n            \n            # Method 2: Code parameters only\n            inspector = YoloInspector(\n                model_path='./best.pt',\n                expected_counts={'apple': 5}\n            )\n            \n            # Method 3: Hybrid approach\n            inspector = YoloInspector(\n                'config/default_config.yaml',\n                confidence_threshold=0.8\n            )\n        \"\"\"\n    \n    def inspect_image(self, image_path: str, detection_mode: str = 'full') -\u003e Dict\n        \"\"\"Detect objects in image\n        \n        Args:\n            image_path: Path to image file\n            detection_mode: 'full' for full image or 'roi' for ROI detection\n        \n        Returns:\n            Detection result dictionary\n        \"\"\"\n    \n    def save_result_image(self, annotated_image, filename: str) -\u003e str\n        \"\"\"Save detection result image\n        \n        Returns:\n            Path to saved file\n        \"\"\"\n    \n    def get_model_info(self) -\u003e Dict\n        \"\"\"Get model information\"\"\"\n```\n\n### Detection Result Structure\n\n```python\nresult = {\n    'filename': str,                    # Original filename\n    'detection_mode': 'full' | 'roi',  # Detection mode used\n    'detections': [                     # List of all detections\n        {\n            'class_id': int,\n            'class_name': str,\n            'confidence': float,\n            'bbox': [x1, y1, x2, y2],   # Detection box coords\n            'wh': [width, height]\n        },\n        ...\n    ],\n    'analysis': {                       # Analysis results\n        'status': 'PASS' | 'FAIL',\n        'summary': str,                 # Summary message\n        'total_detections': int,\n        'details': [\n            {\n                'class_name': str,\n                'expected': int,        # Expected count\n                'actual': int,          # Actual count\n                'status': 'OK' | 'LACK' | 'EXCESS',\n                'message': str\n            },\n            ...\n        ]\n    },\n    'annotated_image': numpy_array,     # Image with detection boxes\n}\n```\n\n## ❓ FAQ\n\n### Q1: How to locate the model_path?\n\nA: YOLO models are typically saved at:\n```\nruns/detect/train/weights/best.pt\n```\n\nIn config file, you can use:\n```yaml\nmodel_path: \"./models/best.pt\"           # Relative path\nmodel_path: \"/absolute/path/best.pt\"    # Absolute path\nmodel_path: \"~/models/best.pt\"          # Home directory\n```\n\n### Q2: How to find the correct class_name?\n\nA: \n```python\nfrom ultralytics import YOLO\nmodel = YOLO('./models/best.pt')\nprint(model.names)\n# Example output: {0: 'huasa1', 1: 'jiaofa1', ...}\n```\n\nThen use these names in config file:\n```yaml\nexpected_counts:\n  huasa1: 1     # class_name must match exactly\n  jiaofa1: 1\n```\n\n### Q3: What if expected_counts class names don't match model output?\n\nA: Check the following:\n1. Verify model class_name with code above\n2. Check config file spelling (case-sensitive)\n3. Ensure config file is UTF-8 encoded\n\n### Q4: How should ROI coordinates be set?\n\nA: Use relative coordinates (0-1), independent of image size:\n```python\n# For 1920x1080 image\n# Want ROI at (200, 100) with size 300x400\n# Relative coordinates:\nx = 200 / 1920 = 0.104\ny = 100 / 1080 = 0.093\nw = 300 / 1920 = 0.156\nh = 400 / 1080 = 0.370\n```\n\n### Q5: How to fix poor detection accuracy?\n\nA: Adjust these parameters:\n```yaml\nmodel_predict_conf: 0.5    # Lower to detect more objects\nconfidence_threshold: 0.4  # Further reduce filter threshold\n```\n\n## 📄 License\n\n[MIT License](https://github.com/Json031/yolo_inspection_kit/blob/main/LICENSE)\n\n## 🤝 Contributing\n\nIssues and Pull Requests are welcome!\n\n## 📞 Contact\n\nIf you have questions, please submit an Issue on GitHub.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjson031%2Fyolo_inspection_kit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjson031%2Fyolo_inspection_kit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjson031%2Fyolo_inspection_kit/lists"}