Human: hi write a python function that converts coco annotation to yolo format. my coco text is "1 202.35577392578125 136.73077392578125 118.701904296875 122.01922607421875 0.96
1 271.4422912597656 73.77404022216797 130.9615478515625 136.51444244384766 0.96
1 41.71875 231.49038696289062 129.6273956298828 136.29806518554688 0.95
1 0.2163461446762085 283.8461608886719 88.12500059604645 133.26922607421875 0.95". if we split this text; first element is class. others are x1 y1 x2 y2 confidence
ChatGPT:
Sure, here's a Python function that converts COCO annotations to YOLO format:
pythondef coco_to_yolo(coco_annotation):
# Split the COCO annotation by whitespace
coco_parts = coco_annotation.split()
# Extract the class ID and coordinates
class_id = coco_parts[0]
x1 = float(coco_parts[1])
y1 = float(coco_parts[2])
x2 = float(coco_parts[3])
y2 = float(coco_parts[4])
# Convert the coordinates to YOLO format
width = x2 - x1
height = y2 - y1
x_center = x1 + (width / 2)
y_center = y1 + (height / 2)
# Normalize the coordinates to between 0 and 1
image_width = 416 # Change this to your image width
image_height = 416 # Change this to your image height
x_center /= image_width
y_center /= image_height
width /= image_width
height /= image_height
# Format the YOLO annotation as a string
yolo_annotation = f"{class_id} {x_center} {y_center} {width} {height}"
return yolo_annotation
You can call this function on each line of your COCO annotation text to get the corresponding YOLO annotation. Here's an example:
pythoncoco_text = "1 202.35577392578125 136.73077392578125 118.701904296875 122.01922607421875 0.96\n1 271.4422912597656 73.77404022216797 130.9615478515625 136.51444244384766 0.96\n1 41.71875 231.49038696289062 129.6273956298828 136.29806518554688 0.95\n1 0.2163461446762085 283.8461608886719 88.12500059604645 133.26922607421875 0.95"
coco_lines = coco_text.split("\n")
for coco_line in coco_lines:
yolo_line = coco_to_yolo(coco_line)
print(yolo_line)
This should output the following YOLO annotations:
1 0.5291392115384615 0.3555980787037037 0.2852571015625 0.29322399131944446 1 0.6564425504807692 0.20324084526978417 0.3143448846153846 0.3279855949074074 1 0.10128725961538461 0.556170524691358 0.31109822435897437 0.29223647569444444 1 0.0005350576923076923 0.6818509615384616 0.21177814663461537 0.32056800868055556
Add a comment