Vassa007

augmentasi

Feb 15th, 2025 (edited)
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.10 KB | None | 0 0
  1. import os
  2. import cv2
  3. import numpy as np
  4. import random
  5. from tqdm.notebook import tqdm # Progress bar
  6. from IPython.display import display, Markdown
  7.  
  8. # Direktori input dan output
  9. INPUT_FOLDER = "assets/anotated" # Folder hasil anotasi sebelumnya
  10. OUTPUT_FOLDER = "assets/augmentasi" # Folder hasil augmentasi
  11.  
  12. # Pastikan output folder tersedia
  13. os.makedirs(OUTPUT_FOLDER, exist_ok=True)
  14.  
  15. # Fungsi flipping bounding box
  16. def flip_bounding_box(image_shape, bbox, flip_code):
  17. height, width = image_shape[:2]
  18. x_center, y_center, box_width, box_height, class_id = bbox
  19.  
  20. if flip_code == 1: # Horizontal flip
  21. x_center = 1.0 - x_center
  22. elif flip_code == 0: # Vertical flip
  23. y_center = 1.0 - y_center
  24. elif flip_code == -1: # Horizontal + Vertical flip
  25. x_center = 1.0 - x_center
  26. y_center = 1.0 - y_center
  27.  
  28. return x_center, y_center, box_width, box_height, class_id
  29.  
  30. # Fungsi untuk membaca anotasi YOLO dalam setiap folder ID personal
  31. def load_annotations(folder):
  32. annotations = {}
  33.  
  34. for person_id in os.listdir(folder):
  35. person_path = os.path.join(folder, person_id)
  36. if not os.path.isdir(person_path):
  37. continue # Skip jika bukan folder
  38.  
  39. for filename in os.listdir(person_path):
  40. if filename.endswith('.txt'):
  41. path = os.path.join(person_path, filename)
  42. with open(path, "r") as f:
  43. lines = f.readlines()
  44. annotations[f"{person_id}/{filename.replace('.txt', '.jpg')}"] = [
  45. tuple(map(float, line.strip().split()[1:])) + (int(line.strip().split()[0]),)
  46. for line in lines
  47. ]
  48. return annotations
  49.  
  50. # Fungsi menyimpan anotasi dalam format YOLO
  51. def save_augmented_annotations(filename, person_id, output_dir, annotations):
  52. person_output_folder = os.path.join(output_dir, person_id)
  53. os.makedirs(person_output_folder, exist_ok=True)
  54.  
  55. txt_output_path = os.path.join(person_output_folder, filename.replace('.jpg', '.txt'))
  56. with open(txt_output_path, "w") as f:
  57. for x_center, y_center, width, height, class_id in annotations:
  58. f.write(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")
  59.  
  60. # Fungsi berbagai augmentasi
  61. def apply_augmentations(image, annotations):
  62. augmented_images = []
  63.  
  64. # 1. Flipping Horizontal
  65. flipped_h = cv2.flip(image, 1)
  66. flipped_h_ann = [flip_bounding_box(image.shape, ann, 1) for ann in annotations]
  67. augmented_images.append((flipped_h, flipped_h_ann, "flipH"))
  68.  
  69. # 2. Rotation (-10 to +10 degrees)
  70. angle = random.randint(-10, 10)
  71. h, w = image.shape[:2]
  72. M = cv2.getRotationMatrix2D((w/2, h/2), angle, 1)
  73. rotated = cv2.warpAffine(image, M, (w, h))
  74. augmented_images.append((rotated, annotations, f"rotate{angle}"))
  75.  
  76. # 3. Gaussian Blur
  77. blurred = cv2.GaussianBlur(image, (5, 5), 0)
  78. augmented_images.append((blurred, annotations, "blur"))
  79.  
  80. # 4. Grayscale
  81. grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  82. grayscale = cv2.cvtColor(grayscale, cv2.COLOR_GRAY2BGR)
  83. augmented_images.append((grayscale, annotations, "gray"))
  84.  
  85. # 5. Brightness & Contrast
  86. alpha = random.uniform(0.8, 1.2) # Contrast
  87. beta = random.randint(-20, 20) # Brightness
  88. bright_contrast = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
  89. augmented_images.append((bright_contrast, annotations, f"bright{beta}_contrast{alpha:.1f}"))
  90.  
  91. # 6. Noise Injection
  92. noise = np.random.normal(0, 10, image.shape).astype(np.uint8)
  93. noisy_image = cv2.add(image, noise)
  94. augmented_images.append((noisy_image, annotations, "noise"))
  95.  
  96. # 7. Perspective Transform (Small Distortion)
  97. pts1 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])
  98. shift_x = random.randint(-10, 10)
  99. shift_y = random.randint(-10, 10)
  100. pts2 = np.float32([[shift_x, shift_y], [w-shift_x, shift_y], [shift_x, h-shift_y], [w-shift_x, h-shift_y]])
  101. matrix = cv2.getPerspectiveTransform(pts1, pts2)
  102. perspective = cv2.warpPerspective(image, matrix, (w, h))
  103. augmented_images.append((perspective, annotations, "perspective"))
  104.  
  105. return augmented_images
  106.  
  107. # Fungsi utama augmentasi dengan progress bar
  108. def augment_images():
  109. person_folders = [f for f in os.listdir(INPUT_FOLDER) if os.path.isdir(os.path.join(INPUT_FOLDER, f))]
  110. annotations_dict = load_annotations(INPUT_FOLDER)
  111.  
  112. if not person_folders:
  113. display(Markdown("❌ **Folder input kosong atau tidak ada gambar!**"))
  114. return
  115.  
  116. total_files = sum(len(files) for _, _, files in os.walk(INPUT_FOLDER))
  117. success_count, failed_count = 0, 0
  118.  
  119. progress = tqdm(person_folders, desc="🔄 Memproses Augmentasi", unit="folder", leave=False)
  120.  
  121. for person_id in progress:
  122. person_path = os.path.join(INPUT_FOLDER, person_id)
  123. output_person_folder = os.path.join(OUTPUT_FOLDER, person_id)
  124. os.makedirs(output_person_folder, exist_ok=True)
  125.  
  126. for filename in os.listdir(person_path):
  127. if filename.endswith(('.jpg', '.jpeg', '.png')):
  128. img_path = os.path.join(person_path, filename)
  129. image = cv2.imread(img_path)
  130.  
  131. if image is None:
  132. failed_count += 1
  133. continue
  134.  
  135. annotations = annotations_dict.get(f"{person_id}/{filename}", [])
  136.  
  137. # Melakukan augmentasi
  138. augmented_images = apply_augmentations(image, annotations)
  139.  
  140. for aug_image, aug_annotations, aug_type in augmented_images:
  141. aug_filename = f"{os.path.splitext(filename)[0]}_{aug_type}.jpg"
  142. cv2.imwrite(os.path.join(output_person_folder, aug_filename), aug_image)
  143. save_augmented_annotations(aug_filename, person_id, OUTPUT_FOLDER, aug_annotations)
  144.  
  145. success_count += 1
  146.  
  147. progress.close()
  148.  
  149. display(Markdown(f"✅ **Proses augmentasi selesai!**"))
  150. display(Markdown(f"📂 **Total file input: {total_files}**"))
  151.  
  152. # Jalankan augmentasi
  153. augment_images()
  154.  
Add Comment
Please, Sign In to add comment