Skip to content

Commit

Permalink
yolosegment2labelme
Browse files Browse the repository at this point in the history
  • Loading branch information
Abonia1 committed May 7, 2024
1 parent 78dad02 commit efcc0a9
Show file tree
Hide file tree
Showing 99 changed files with 32,862 additions and 1 deletion.
Binary file added .DS_Store
Binary file not shown.
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2018 The Python Packaging Authority

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
75 changes: 74 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,74 @@
# yolosegment_to_labelmejson
# yolosegment2labelme

**yolosegment2labelme** is a Python package that allows you to convert YOLO segmentation prediction results to LabelMe JSON format. This tool facilitates the annotation process by generating JSON files that are compatible with LabelMe and other labeling annotation tools.

## Features

- Convert YOLO segmentation prediction results to LabelMe JSON format.
- Compatible with various YOLO models.
- Easy-to-use command-line interface.
- Supports batch processing of images.
- Customizable confidence threshold for predictions.
- Highly customizable and extensible for specific use cases.

## Installation

You can install **yolosegment2labelme** via pip:

```bash
pip install yolosegment2labelme
```

## Usage

After installation, you can use the `yolosegment2labelme` command-line interface to convert YOLO segmentation prediction results to LabelMe JSON format. Here's a basic example:

```bash
yolosegment2labelme --images /path/to/images
```

or with custom yolo segmentation model

```bash
yolosegment2labelme --model yolov8n-seg.pt --images /path/to/images --conf 0.3
```

This command will process the images located in the specified directory (`/path/to/images`), using the YOLO model weights file `yolov8n-seg.pt`, and generate LabelMe JSON files with a confidence threshold of 0.3.

For more options and advanced usage, refer to the [documentation](https://github.com/Abonia1/yolosegment2labelme).

## Sample Images
The table below displays sample images along with their corresponding annotations generated using yolosegment2labelme:

## Sample Images

| Sample Image 1 | Sample Image 2 |
|-----------------------------------------------------|-----------------------------------------------------|
| ![Sample Image 1](images/labelme_test/sample1.png) | ![Sample Image 2](images/labelme_test/sample2.png) |
| Sample Annotation for Image 1 | Sample Annotation for Image 2 |

| Sample Image 3 | Sample Image 4 |
|-----------------------------------------------------|-----------------------------------------------------|
| ![Sample Image 3](images/labelme_test/sample3.png) | ![Sample Image 4](images/labelme_test/sample4.png) |
| Sample Annotation for Image 3 | Sample Annotation for Image 4 |


## Documentation

The documentation for **yolosegment2labelme** can be found on GitHub: [yolosegment2labelme Documentation](https://github.com/Abonia1/yolosegment2labelme)

## Contributing

Contributions are welcome! If you'd like to contribute to **yolosegment2labelme**, please check out the [Contribution Guidelines](CONTRIBUTING.md).

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Authors

- Abonia Sojasingarayar - [GitHub](https://github.com/Abonia1)

## Support

If you encounter any issues or have questions about **yolosegment2labelme**, please feel free to open an issue on GitHub: [yolosegment2labelme Issues](https://github.com/Abonia1/yolosegment2labelme/issues)
Empty file.
86 changes: 86 additions & 0 deletions build/lib/yolosegment2labelme/polygon_saver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import json
import cv2
import os

class PolygonSaver:
"""
Class to save image information along with polygon shapes and xy coordinates to a JSON file.
"""
def __init__(self):
pass

def save_image_info_with_polygons(self, image_path, xy_coordinates, label_name, output_dir):
"""
Save image information along with polygon shapes and xy coordinates to a JSON file.
If the JSON file already exists, append the new mask information to it.
Args:
image_path (str): Path to the image file.
xy_coordinates (list): List of xy coordinates.
label_name (str): Label name for the polygon shapes.
output_dir (str): Directory to save the JSON file.
"""
image = cv2.imread(image_path)
height, width = image.shape[:2]

json_data = {
"version": "0.3.3",
"flags": {},
"shapes": [],
"imagePath": os.path.basename(image_path),
"imageData": None,
"imageHeight": height,
"imageWidth": width,
"text": ""
}

xy_coordinate_as_lists = [xy_coordinate.tolist() for xy_coordinate in xy_coordinates]

json_data["shapes"].append({
"label": label_name,
"text": "",
"points": xy_coordinate_as_lists,
"group_id": None,
"shape_type": "polygon",
"flags": {}
})

for shape in json_data['shapes']:
for point in shape['points']:
shape['points'] = point

json_file_name = os.path.join(output_dir, os.path.basename(image_path).replace(os.path.splitext(image_path)[1], ".json"))

if os.path.exists(json_file_name):
with open(json_file_name, 'r') as json_file:
existing_data = json.load(json_file)

existing_data["shapes"].extend(json_data["shapes"])

with open(json_file_name, 'w') as json_file:
json.dump(existing_data, json_file, indent=2)
else:
with open(json_file_name, 'w') as json_file:
json.dump(json_data, json_file, indent=2)

print(f"Polygon information saved for {image_path} with label {label_name}")

def generate_json_with_results(self, results, output_dir):
"""
Generate JSON files with results obtained from YOLO model predictions.
Args:
results (list): List of results obtained from YOLO model predictions.
output_dir (str): Directory to save the JSON files.
"""
for result in results:
if result.masks is None:
continue
class_labels = result.boxes.cls.cpu().numpy()
label_names = {k: v for k, v in result.names.items()}

for mask, class_label in zip(result.masks, class_labels):
xy_coordinates = mask.xy
image_path = result.path
label_name = label_names[int(class_label)]
self.save_image_info_with_polygons(image_path, xy_coordinates, label_name, output_dir)
28 changes: 28 additions & 0 deletions build/lib/yolosegment2labelme/yolosegment2labelme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import argparse
from polygon_saver import PolygonSaver
from ultralytics import YOLO

def main():
parser = argparse.ArgumentParser(description='Convert YOLO results to JSON files.')
parser.add_argument('--model', default='yolov8n-seg.pt', help='Path to YOLO model weights file (default is yolov8n)')
parser.add_argument('--images', required=True, help='Path to folder containing images')
parser.add_argument('--conf', type=float, default=0.2, help='Confidence threshold')
args = parser.parse_args()

# Use the input images directory as the output directory for JSON files
output_dir = args.images

# Instantiate the PolygonSaver class
polygon_saver = PolygonSaver()

# Load the YOLO model
yolo_model = YOLO(args.model)

# Get results from YOLO model predictions
results = yolo_model.predict(args.images, save=True, conf=args.conf)

# Generate JSON files with results
polygon_saver.generate_json_with_results(results, output_dir)

if __name__ == "__main__":
main()
Binary file added dist/yolosegment2labelme-0.0.1-py3-none-any.whl
Binary file not shown.
Binary file added dist/yolosegment2labelme-0.0.1.tar.gz
Binary file not shown.
Binary file added images/.DS_Store
Binary file not shown.
Binary file added images/1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit efcc0a9

Please sign in to comment.