Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

prepare.py 2.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  1. import os
  2. import random
  3. import argh
  4. val_ratio = 0.2
  5. def prepare(images_dir, yolo_labels_dir, output_dir):
  6. """
  7. Prepare data for training
  8. """
  9. yolo_labels_dir = os.path.join(yolo_labels_dir, "labels")
  10. image_list = os.listdir(images_dir)
  11. train_lines = []
  12. val_lines = []
  13. for txt_file in os.listdir(yolo_labels_dir):
  14. # Check text file
  15. if not txt_file.endswith(".txt"):
  16. continue
  17. # Check image exists
  18. image_name, _ = os.path.splitext(txt_file)
  19. try:
  20. image_name_with_ext = next(image for image in image_list if image.startswith(image_name))
  21. except StopIteration:
  22. print("Image {} not found".format(image_name))
  23. continue
  24. # Extract labels
  25. with open(os.path.join(yolo_labels_dir, txt_file), "r") as f:
  26. image_labels = []
  27. for label_data in f.read().splitlines():
  28. obj_class, x, y, width, height = label_data.split(" ")
  29. x, y, width, height = float(x), float(y), float(width), float(height)
  30. x2, y2 = x + width, y + height
  31. size = 608
  32. x, y, x2, y2 = str(x * size), str(y * size), str(x2 * size), str(y2 * size)
  33. train_format_label = ",".join([x, y, x2, y2, obj_class])
  34. image_labels.append(train_format_label)
  35. if random.uniform(0, 1) < val_ratio:
  36. val_lines.append("{} {}".format(image_name_with_ext, " ".join(image_labels)))
  37. else:
  38. train_lines.append("{} {}".format(image_name_with_ext, " ".join(image_labels)))
  39. os.makedirs(output_dir, exist_ok=True)
  40. with open(os.path.join(output_dir, "train.txt"), "w") as f:
  41. f.write("\n".join(train_lines))
  42. with open(os.path.join(output_dir, "val.txt"), "w") as f:
  43. f.write("\n".join(val_lines))
  44. # assembling:
  45. parser = argh.ArghParser()
  46. parser.add_commands([
  47. prepare,
  48. ])
  49. if __name__ == "__main__":
  50. parser.dispatch()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...