Nekshay commited on
Commit
70f3968
·
verified ·
1 Parent(s): 86f62fd

Update code.txt

Browse files
Files changed (1) hide show
  1. code.txt +65 -0
code.txt CHANGED
@@ -259,4 +259,69 @@ function ObjectDetector() {
259
 
260
  export default ObjectDetector;
261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
 
259
 
260
  export default ObjectDetector;
261
 
262
+
263
+
264
+ import json
265
+ import random
266
+ import os
267
+
268
+ # Load the COCO annotations file
269
+ coco_file = 'annotations.json' # Path to your COCO annotations file
270
+ output_dir = 'output_dir/' # Directory to save the split files
271
+ train_ratio = 0.8 # 80% for training, 20% for validation
272
+
273
+ # Create output directory if it doesn't exist
274
+ if not os.path.exists(output_dir):
275
+ os.makedirs(output_dir)
276
+
277
+ # Load COCO annotations
278
+ with open(coco_file, 'r') as f:
279
+ coco_data = json.load(f)
280
+
281
+ # Extract images and annotations
282
+ images = coco_data['images']
283
+ annotations = coco_data['annotations']
284
+
285
+ # Shuffle images to ensure random split
286
+ random.shuffle(images)
287
+
288
+ # Split images into training and validation sets
289
+ train_size = int(len(images) * train_ratio)
290
+ train_images = images[:train_size]
291
+ val_images = images[train_size:]
292
+
293
+ # Create dictionaries to store image IDs for filtering annotations
294
+ train_image_ids = {img['id'] for img in train_images}
295
+ val_image_ids = {img['id'] for img in val_images}
296
+
297
+ # Split annotations based on image IDs
298
+ train_annotations = [ann for ann in annotations if ann['image_id'] in train_image_ids]
299
+ val_annotations = [ann for ann in annotations if ann['image_id'] in val_image_ids]
300
+
301
+ # Create train and validation splits for COCO format
302
+ train_data = {
303
+ 'images': train_images,
304
+ 'annotations': train_annotations,
305
+ 'categories': coco_data['categories'], # Keep categories the same
306
+ }
307
+
308
+ val_data = {
309
+ 'images': val_images,
310
+ 'annotations': val_annotations,
311
+ 'categories': coco_data['categories'], # Keep categories the same
312
+ }
313
+
314
+ # Save the new train and validation annotation files
315
+ train_file = os.path.join(output_dir, 'train_annotations.json')
316
+ val_file = os.path.join(output_dir, 'val_annotations.json')
317
+
318
+ with open(train_file, 'w') as f:
319
+ json.dump(train_data, f)
320
+
321
+ with open(val_file, 'w') as f:
322
+ json.dump(val_data, f)
323
+
324
+ print(f"Train annotations saved to: {train_file}")
325
+ print(f"Validation annotations saved to: {val_file}")
326
+
327