CVRPDataset commited on
Commit
583a2cc
·
verified ·
1 Parent(s): 7a13e58

Upload rgb2gray.py

Browse files
Files changed (1) hide show
  1. run/rgb2gray.py +46 -0
run/rgb2gray.py ADDED
@@ -0,0 +1,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
+
30
+
31
+ for img_name in os.listdir(img_dir):
32
+ try:
33
+ img_path = os.path.join(img_dir, img_name)
34
+ mask_path = os.path.join(ann_target_dir, f'{os.path.splitext(img_name)[0]}.png')
35
+
36
+ rgb_to_binary_mask(img_path, mask_path)
37
+
38
+ except Exception as e:
39
+ print(f"Failed to convert {img_name}: {e}")
40
+
41
+ print("Conversion completed.")
42
+
43
+
44
+ if __name__ == '__main__':
45
+ Dataset_Path = 'J:/dataset_panicle'
46
+ convert_rgb_to_binary(Dataset_Path)