File size: 3,800 Bytes
730a0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import os
import cv2
import numpy as np
from tqdm import tqdm

def extract_masked_region(img: np.ndarray,
                          msk: np.ndarray,
                          threshold: int = 127,
                          crop: bool = True) -> np.ndarray:
    # Binarize mask
    _, bin_mask = cv2.threshold(msk, threshold, 255, cv2.THRESH_BINARY)
    # Apply mask
    result = cv2.bitwise_and(img, img, mask=bin_mask)
    if crop:
        ys, xs = np.where(bin_mask == 255)
        if ys.size and xs.size:
            y1, y2 = ys.min(), ys.max()
            x1, x2 = xs.min(), xs.max()
            result = result[y1:y2+1, x1:x2+1]
    return result

def batch_process(collage_dir: str,
                  mask_dir:    str,
                  out_dir:     str):
    os.makedirs(out_dir, exist_ok=True)

    files = [f for f in os.listdir(collage_dir)
             if f.lower().endswith(('.png','.jpg','.jpeg','.bmp','tif','tiff'))]
    for fname in tqdm(files, desc="Processing images"):
        img_path  = os.path.join(collage_dir, fname)
        mask_path = os.path.join(mask_dir,    fname)
        out_path  = os.path.join(out_dir,     fname)

        if not os.path.isfile(mask_path):
            tqdm.write(f"⚠️  mask not found for {fname}, skipping")
            continue

        img = cv2.imread(img_path, cv2.IMREAD_COLOR)
        msk = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
        if img is None or msk is None:
            tqdm.write(f"⚠️  failed to load {fname} or its mask, skipping")
            continue

        cropped = extract_masked_region(img, msk, threshold=127, crop=True)
        cv2.imwrite(out_path, cropped)

    tqdm.write("✅ All done!")

if __name__ == "__main__":
    # adjust these paths as needed:
    collage_folder = "/home/darth/#/WaterMeters/images"
    mask_folder    = "/home/darth/#/WaterMeters/masks"
    output_folder  = "/home/darth/#/WaterMeters/cropped"

    batch_process(collage_folder, mask_folder, output_folder)


# import cv2
# import numpy as np

# def extract_masked_region(image_path: str,
#                           mask_path: str,
#                           threshold: int = 127,
#                           crop: bool = True):
#     """
#     Loads an image and its mask, applies the mask, and returns the resulting image.
#     If crop=True, it also crops to the bounding box of the white region in the mask.

#     :param image_path:   Path to the original BGR image.
#     :param mask_path:    Path to the grayscale mask (white=keep, black=discard).
#     :param threshold:    Grayscale threshold to binarize the mask (0–255).
#     :param crop:         If True, crop to the mask's bounding box.
#     :return:             A BGR image with only the masked region (and optionally cropped).
#     """
#     # 1. Load images
#     img  = cv2.imread(image_path, cv2.IMREAD_COLOR)
#     msk  = cv2.imread(mask_path,  cv2.IMREAD_GRAYSCALE)
#     if img is None or msk is None:
#         raise FileNotFoundError("Could not load image or mask. Check your paths.")

#     # 2. Binarize mask
#     _, bin_mask = cv2.threshold(msk, threshold, 255, cv2.THRESH_BINARY)

#     # 3. Apply mask
#     result = cv2.bitwise_and(img, img, mask=bin_mask)

#     if crop:
#         # 4. Find bounding box of white region
#         ys, xs = np.where(bin_mask == 255)
#         if ys.size and xs.size:
#             y1, y2 = ys.min(), ys.max()
#             x1, x2 = xs.min(), xs.max()
#             result = result[y1:y2+1, x1:x2+1]

#     return result

# if __name__ == "__main__":
#     out = extract_masked_region("/home/darth/#/WaterMeters/collage/id_1_value_13_116.jpg", "/home/darth/#/WaterMeters/masks/id_1_value_13_116.jpg")
#     cv2.imwrite("meter_extracted.png", out)
#     print("Saved extracted region to meter_extracted.png")