Delete yolo-instance-segmentation.ipynb
Browse files
yolo-instance-segmentation.ipynb
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"accelerator":"GPU","colab":{"collapsed_sections":["lyEgEiuUkXZU","71AHeJqUjyQY"],"gpuType":"T4","provenance":[]},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":31012,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install ultralytics\n!pip install roboflow","metadata":{"id":"bmbwkNw5iNvu","colab":{"base_uri":"https://localhost:8080/"},"outputId":"28ba78d2-f702-4c4b-d6c7-4f4d2b023c9f","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nfrom roboflow import Roboflow\nimport os","metadata":{"id":"h7oilhOylS-K","colab":{"base_uri":"https://localhost:8080/"},"outputId":"b7019df8-348b-40b3-93a8-2837d981ba2f","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Data Download**","metadata":{"id":"D1T5EmCAqmz8"}},{"cell_type":"code","source":"!wget https://huggingface.co/datasets/abturjo/25_75_overlap/resolve/main/tiles_JPG_25.zip\n!wget https://huggingface.co/datasets/abturjo/25_75_overlap/resolve/main/tiles_JPG_75.zip","metadata":{"id":"zhVWWSw3qjpk","colab":{"base_uri":"https://localhost:8080/"},"outputId":"f368f066-fd33-4c5f-a905-4e115a61fd09","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!unzip tiles_JPG_25.zip\n!unzip tiles_JPG_75.zip","metadata":{"id":"gbuFPqKhrhuR","colab":{"base_uri":"https://localhost:8080/"},"outputId":"ae814901-f5a8-4852-ab21-3e8517f5a487","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!wget https://huggingface.co/abturjo/YOLO_Instance_Segmentation_Train/resolve/main/best_v11m.pt\n!wget https://huggingface.co/abturjo/YOLO_Instance_Segmentation_Train/resolve/main//best_v8m.pt","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Weights download**","metadata":{"id":"M537KIM8abGb"}},{"cell_type":"code","source":"!wget 'https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11m-seg.pt'\n!wget 'https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11s-seg.pt'","metadata":{"id":"56aIbEhpYBWx","colab":{"base_uri":"https://localhost:8080/"},"outputId":"3366ca44-c8c6-43dc-ba09-db431d0c3519","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model: YOLO\n---\n**Version: v8n**","metadata":{"id":"WXGOEpbTkb-u"}},{"cell_type":"markdown","source":"## Train","metadata":{"id":"LcgG_Y_Gkaee"}},{"cell_type":"code","source":"# Normal train-set\n# rf = Roboflow(api_key=\"cIEHAX4VyYolY0CtAbnT\")\n# project = rf.workspace(\"sam-on-building-detection\").project(\"mt-seg-ann-1024_compressed_cv2\")\n# version = project.version(19)\n# dataset = version.download(\"yolov9\")\n\nfrom roboflow import Roboflow\nrf = Roboflow(api_key=\"cIEHAX4VyYolY0CtAbnT\")\nproject = rf.workspace(\"building-segmentation-traintest-bcha5\").project(\"mt-seg-ann-1024_compressed_cv2\")\nversion = project.version(22)\ndataset = version.download(\"yolov8\")\n\n# You may need to change the import settings based on your forked project (Yes, it's recommended that you fork these projects)\n","metadata":{"id":"W01cY0CvPrH2","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Augmented for OBB training (v8 obb format export)\nrf = Roboflow(api_key=\"cIEHAX4VyYolY0CtAbnT\")\nproject = rf.workspace(\"building-segmentation-traintest-bcha5\").project(\"mt-seg-ann-1024_compressed_cv2\")\nversion = project.version(21)\ndataset = version.download(\"yolov8-obb\")\n","metadata":{"id":"aIqqHCeCe6pp","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\n\n# Load a pretrained YOLOv8 segmentation model\n# 'yolov11m-seg.pt' is required to be separately downloaded, but 'yolov8m-seg.pt' would work with only the constructor command\nmodel = YOLO('yolo11m-seg.pt') # You can choose 'yolov8m-seg.pt', etc., based on your preference\n\n# Train the model using the dataset\n# model.train(data=f'{dataset.location}/data.yaml', epochs=100, batch=8, imgsz=1024)\nmodel.train(data='/content/onestepDataset/data.yaml', epochs=100, batch=8, imgsz=1024)\n","metadata":{"id":"-kMGlWVqmzJ_","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Validation","metadata":{"id":"lyEgEiuUkXZU"}},{"cell_type":"code","source":"results = model.val()","metadata":{"id":"r--2RGNOxphJ","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Test","metadata":{"id":"iIa4R29bkU_I"}},{"cell_type":"code","source":"# Test-Set (200 images)\n\n# rf = Roboflow(api_key=\"ZFVhsxTkMfwSCbbUm8UK\")\n# project = rf.workspace(\"thesis19\").project(\"test_komlapur_50p_overlap_x2048\")\n# version = project.version(1)\n# dataset = version.download(\"yolov9\")\n\n\nrf = Roboflow(api_key=\"ZFVhsxTkMfwSCbbUm8UK\")\nproject = rf.workspace(\"thesis19\").project(\"test_komlapur_50p_overlap_x2048\")\nversion = project.version(2)\ndataset = version.download(\"yolov9\")\n","metadata":{"id":"4jqqfmXuAUPb","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Test-Set (52 images)\nrf = Roboflow(api_key=\"cIEHAX4VyYolY0CtAbnT\")\nproject = rf.workspace(\"building-segmentation-traintest-bcha5\").project(\"kpur-seg-ann-1024-compressed-cv2\")\nversion = project.version(5)\ndataset = version.download(\"yolov9\")\n","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"4A_grthncf2U","outputId":"753dcf93-e8f9-4ae9-9fbf-88bb6708abeb","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict and visualize results on test images\ntest_images_path = '/content/tiles_JPG_75'\n\nmodel = YOLO('/content/segment/train/weights/best.pt')\nresults = model.predict(source=test_images_path, imgsz=1024, conf=0.8, save=True, save_txt=True, save_conf=True) # Use save=True to save the results","metadata":{"id":"Mdgznt4ByXLW","colab":{"base_uri":"https://localhost:8080/","height":1000},"outputId":"cc6bb2f2-5d9a-473c-a831-9c6e664459ae","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !rm -Rf '/content/200_masks_yolov11'\n","metadata":{"id":"D3Ty2MUKJAF8","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Single Mask Save","metadata":{"id":"r5_Ot_Fhjtgx"}},{"cell_type":"code","source":"# Single Mask Saves\nimport numpy as np\nimport cv2\nimport os\n\nimage_height = 2048\nimage_width = 2048\nsave_path = '/content/200_masks_yolov8m'\n\nos.makedirs(save_path, exist_ok=True)\n\nfor index, result in enumerate(results):\n folder_name = os.path.splitext(os.path.basename(result.path))[0]\n folder_path = os.path.join(save_path, folder_name)\n os.makedirs(folder_path, exist_ok=True)\n\n background = np.zeros((image_height, image_width), dtype=np.uint8)\n\n if result.masks is None:\n print(os.path.basename(result.path), ' file has no masks')\n continue\n\n masks = result.masks.xy\n\n for i, mask in enumerate(masks):\n points = np.array(mask, dtype=np.int32).reshape((-1, 1, 2))\n cv2.fillPoly(background, [points], 255)\n individual_mask_save_path = os.path.join(folder_path, f'mask_{i+1}.png')\n cv2.imwrite(individual_mask_save_path, background)\n background = np.zeros((image_height, image_width), dtype=np.uint8)\n\n print(f'Processed file: {os.path.basename(result.path)}')\n","metadata":{"id":"gnjcg1oZVO26","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Masks per image save","metadata":{"id":"71AHeJqUjyQY"}},{"cell_type":"code","source":"import numpy as np\nimport cv2\nimport os\n\nimage_height = 1024\nimage_width = 1024\nsave_path = '/content/52_masks_yolov11m'\n\nos.makedirs(save_path, exist_ok=True)\n\nfor index, result in enumerate(results):\n folder_name = os.path.splitext(os.path.basename(result.path))[0]\n folder_path = os.path.join(save_path, folder_name)\n\n # Combined mask image save path\n combined_mask_save_path = folder_path + '.png'\n\n # Create a single background to hold all masks for the image\n background = np.zeros((image_height, image_width), dtype=np.uint8)\n\n if result.masks is None:\n print(os.path.basename(result.path), ' file has no masks')\n cv2.imwrite(combined_mask_save_path, background)\n continue\n\n masks = result.masks.xy\n\n # Loop through all masks and draw them on the same background\n for mask in masks:\n points = np.array(mask, dtype=np.int32).reshape((-1, 1, 2))\n cv2.fillPoly(background, [points], 255)\n\n # Save the combined mask image\n cv2.imwrite(combined_mask_save_path, background)\n\n print(f'Processed file: {os.path.basename(result.path)}')\n print(\"Masks found -->\", len(masks))\n","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"4FIqlSmqj3Kh","outputId":"aaa851b1-6e51-487f-b1e8-4b967d76f585","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Saving masks with confidence score","metadata":{"id":"YGoNgkpwh3Mk"}},{"cell_type":"code","source":"# Delete Directory\n!rm -r labels_11m/","metadata":{"id":"0n05Dsk6iCV7","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\nmasks_save_dir = '/content/labels_8m_75'\nos.makedirs(masks_save_dir, exist_ok=True)\n\nfor index, result in enumerate(results):\n classes = result.boxes.cls\n masks = result.masks\n confs = result.boxes.conf\n filename = result.path.split('/')[-1]\n # pos = filename.strip().split('_')[2].split('-')[1:3]\n pos = filename.split('_')[3:5]\n\n if masks is not None:\n for i, mask in enumerate(masks):\n mask_filename = f\"{index+1}_{pos[0]}-{pos[1]}.txt\"\n mask_filepath = os.path.join(masks_save_dir, mask_filename)\n\n # Flatten mask coordinates and convert to list\n mask = mask.xy[0].flatten().tolist()\n\n # Append confidence score to the end of the mask list\n mask.append(confs[i].item())\n # Prepend the class_id\n mask.insert(0, int(classes[i].item()))\n\n # Convert to a space-separated string\n mask_string = ' '.join(map(str, mask))\n\n # Write to file\n with open(mask_filepath, 'a') as f:\n f.write(f\"{mask_string}\\n\")\n\n","metadata":{"id":"gCxHngcMh2Yk","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# File Download Section","metadata":{"id":"h8IvZSpOj4AQ"}},{"cell_type":"code","source":"import zipfile\nimport shutil\nimport os\n\n\nzip_path = '/content/labels_11m'\n\n# Create a ZIP file\nshutil.make_archive(zip_path, 'zip', zip_path)","metadata":{"colab":{"base_uri":"https://localhost:8080/","height":36},"id":"7VWWNZ0WeopD","outputId":"8a51c03c-25a4-4ed0-9a5d-b327da6339a4","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from google.colab import files\n\n# Download the ZIP file\nfiles.download(zip_path)","metadata":{"id":"oIeL4_7j8suC","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!cp -r '/content/labels_8m' '/content/drive/MyDrive/labels_8m'","metadata":{"id":"jEMRI3Kef3z9","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Habijabi","metadata":{"id":"5petNp7BkvUh"}},{"cell_type":"code","source":"!cp -r '/content/drive/MyDrive/Thesis Results/onestepDataset' '/content'","metadata":{"id":"sp7kwXsTY1UV","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from google.colab import drive\ndrive.mount('/content/drive')","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"JXkjJCWogRCM","outputId":"b8ba4554-8cbc-45e1-f32b-7f29b74f8f26","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import locale\nlocale.getpreferredencoding = lambda: \"UTF-8\"","metadata":{"id":"CSFj5psngrmC","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!cp -r '/content/200_masks_yolov8m' '/content/drive/MyDrive/v11m'","metadata":{"id":"7gLMhQtkNFdh","trusted":true},"outputs":[],"execution_count":null}]}
|
|
|
|
|
|