Update run/transform.py
Browse files- run/transform.py +48 -46
run/transform.py
CHANGED
@@ -1,46 +1,48 @@
|
|
1 |
-
import os
|
2 |
-
import cv2
|
3 |
-
import numpy as np
|
4 |
-
|
5 |
-
|
6 |
-
def rgb_to_binary_mask(img_path, output_path):
|
7 |
-
'''
|
8 |
-
Convert an RGB image to a binary mask where non-black pixels are set to 1, black pixels are 0.
|
9 |
-
'''
|
10 |
-
|
11 |
-
img_bgr = cv2.imread(img_path)
|
12 |
-
|
13 |
-
img_binary_mask = np.zeros(img_bgr.shape[:2], dtype=np.uint8)
|
14 |
-
|
15 |
-
non_black_pixels = np.any(img_bgr != [0, 0, 0], axis=-1)
|
16 |
-
img_binary_mask[non_black_pixels] = 1
|
17 |
-
|
18 |
-
cv2.imwrite(output_path, img_binary_mask)
|
19 |
-
|
20 |
-
|
21 |
-
def convert_rgb_to_binary(Dataset_Path):
|
22 |
-
'''
|
23 |
-
Convert all RGB images in the dataset to binary mask images.
|
24 |
-
'''
|
25 |
-
|
26 |
-
img_dir = os.path.join(Dataset_Path, 'annotation')
|
27 |
-
|
28 |
-
ann_target_dir = os.path.join(Dataset_Path, 'ann_dir')
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
|
6 |
+
def rgb_to_binary_mask(img_path, output_path):
|
7 |
+
'''
|
8 |
+
Convert an RGB image to a binary mask where non-black pixels are set to 1, black pixels are 0.
|
9 |
+
'''
|
10 |
+
|
11 |
+
img_bgr = cv2.imread(img_path)
|
12 |
+
|
13 |
+
img_binary_mask = np.zeros(img_bgr.shape[:2], dtype=np.uint8)
|
14 |
+
|
15 |
+
non_black_pixels = np.any(img_bgr != [0, 0, 0], axis=-1)
|
16 |
+
img_binary_mask[non_black_pixels] = 1
|
17 |
+
|
18 |
+
cv2.imwrite(output_path, img_binary_mask)
|
19 |
+
|
20 |
+
|
21 |
+
def convert_rgb_to_binary(Dataset_Path):
|
22 |
+
'''
|
23 |
+
Convert all RGB images in the dataset to binary mask images.
|
24 |
+
'''
|
25 |
+
|
26 |
+
img_dir = os.path.join(Dataset_Path, 'annotation')
|
27 |
+
|
28 |
+
ann_target_dir = os.path.join(Dataset_Path, 'ann_dir')
|
29 |
+
if not os.path.exists(ann_target_dir):
|
30 |
+
os.mkdir(ann_target_dir)
|
31 |
+
|
32 |
+
|
33 |
+
for img_name in os.listdir(img_dir):
|
34 |
+
try:
|
35 |
+
img_path = os.path.join(img_dir, img_name)
|
36 |
+
mask_path = os.path.join(ann_target_dir, f'{os.path.splitext(img_name)[0]}.png')
|
37 |
+
|
38 |
+
rgb_to_binary_mask(img_path, mask_path)
|
39 |
+
|
40 |
+
except Exception as e:
|
41 |
+
print(f"Failed to convert {img_name}: {e}")
|
42 |
+
|
43 |
+
print("Conversion completed.")
|
44 |
+
|
45 |
+
|
46 |
+
if __name__ == '__main__':
|
47 |
+
Dataset_Path = 'CVRPDataset'
|
48 |
+
convert_rgb_to_binary(Dataset_Path)
|