bhimrazy commited on
Commit
cdb0658
0 Parent(s):

Add utility functions for image processing and tracking files

Browse files
Files changed (1) hide show
  1. src/utils.py +79 -0
src/utils.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from PIL import Image, ImageOps
4
+
5
+
6
+ def crop_and_pad_image(image_path, threshold=20, target_size=(512, 512)):
7
+ """
8
+ Crop and pad an image to a square with the specified target size.
9
+
10
+ Args:
11
+ image_path (str): Path to the input image file.
12
+ threshold (int): Threshold value for binarizing the image.
13
+ target_size (tuple): Target size of the output image (width, height).
14
+
15
+ Returns:
16
+ PIL.Image.Image: Cropped and padded image.
17
+ """
18
+ try:
19
+ # Load the image
20
+ image = Image.open(image_path).convert("RGB")
21
+ except Exception as e:
22
+ raise ValueError(f"Error loading image: {str(e)}")
23
+
24
+ # Convert the image to a NumPy array
25
+ image_array = np.array(image)
26
+
27
+ # Binarize the image
28
+ binary_image_array = np.where(image_array > threshold, 1, 0).astype(np.uint8)
29
+
30
+ # Find non-zero elements (non-black pixels)
31
+ non_zero_indices = np.argwhere(binary_image_array)
32
+
33
+ # Check if non-zero elements exist
34
+ if non_zero_indices.size == 0:
35
+ raise ValueError(f"No non-zero elements found for the image: {image_path}")
36
+
37
+ # Get the bounding box of non-zero elements
38
+ (y1, x1, _), (y2, x2, _) = non_zero_indices.min(0), non_zero_indices.max(0)
39
+
40
+ # Crop the Region of Interest (ROI)
41
+ cropped_img = image.crop((x1, y1, x2, y2))
42
+
43
+ # Pad the image to make it a square
44
+ squared_img = ImageOps.pad(cropped_img, target_size)
45
+
46
+ return squared_img
47
+
48
+
49
+ def track_files(folder_path, extensions=('.jpg', '.jpeg', '.png')):
50
+ """
51
+ Track all the files in a folder and its subfolders.
52
+
53
+ Args:
54
+ folder_path (str): The path of the folder to track files in.
55
+ extensions (tuple, optional): Tuple of file extensions to track. Default is ('.jpg', '.jpeg', '.png').
56
+
57
+ Returns:
58
+ list: A list containing the paths of all files in the folder and its subfolders.
59
+ """
60
+ # Validate folder_path
61
+ if not os.path.isdir(folder_path):
62
+ raise ValueError("Invalid folder path provided.")
63
+
64
+ # Convert extensions to lowercase for case-insensitive comparison
65
+ extensions = tuple(ext.lower() for ext in extensions)
66
+
67
+ # Initialize file_list
68
+ file_list = []
69
+
70
+ # Walk through the folder and its subfolders
71
+ for root, dirs, files in os.walk(folder_path):
72
+ for filename in files:
73
+ file_path = os.path.join(root, filename)
74
+ _, extension = os.path.splitext(file_path)
75
+ # Check if the file extension is in the list of extensions
76
+ if extension.lower() in extensions:
77
+ file_list.append(file_path)
78
+
79
+ return file_list