Coverage for scripts/rename_files.py: 93%

28 statements  

« prev     ^ index     » next       coverage.py v7.10.2, created at 2025-08-07 15:22 +0000

1import os 

2import re 

3 

4def rename_images_labels(dir_path_images, dir_path_labels): 

5 image_files = [f for f in os.listdir(dir_path_images) if os.path.isfile(os.path.join(dir_path_images, f))] 

6 existing_images = set(image_files) 

7 

8 for filename in image_files: 

9 name, ext = os.path.splitext(filename) 

10 full_image_path = os.path.join(dir_path_images, filename) 

11 

12 # Skip non-image files 

13 if ext.lower() not in ['.jpg', '.jpeg', '.png']: 

14 continue 

15 

16 # Clean up base name 

17 new_base = re.sub(r'(_jpg.*)+$', '', name) 

18 candidate = new_base + ext 

19 counter = 1 

20 existing_images.remove(filename) 

21 

22 # Avoid name collisions 

23 while candidate in existing_images: 

24 candidate = f"{new_base}_{counter}{ext}" 

25 counter += 1 

26 

27 existing_images.add(candidate) 

28 

29 if filename != candidate: 

30 # Rename image 

31 new_image_path = os.path.join(dir_path_images, candidate) 

32 os.rename(full_image_path, new_image_path) 

33 print(f"Renamed image: {filename} -> {candidate}") 

34 

35 # Rename corresponding .txt file 

36 old_txt = os.path.join(dir_path_labels, name + '.txt') 

37 new_txt = os.path.join(dir_path_labels, os.path.splitext(candidate)[0] + '.txt') 

38 print(f"Renaming label: {name}.txt to {os.path.splitext(candidate)[0]}.txt") 

39 if os.path.exists(old_txt): 

40 os.rename(old_txt, new_txt) 

41 print(f"Renamed label: {name}.txt -> {os.path.splitext(candidate)[0]}.txt") 

42 

43 

44# image = "../8080/train/" 

45# label = "../8080/labels" 

46# rename_images_labels(image, label)