CoolFace
Apppublic

Pavan2k4/Building_area

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
0likes
split_merge.py53 linesDownload Raw Back to root
1import cv22import os 3import numpy as np 4 5patches_folder = "Patches"6pred_patches = "Patch_pred"7os.makedirs(patches_folder, exist_ok=True)8os.makedirs(pred_patches,exist_ok=True)9 10 11def split(image, destination = patches_folder, patch_size = 256):12    img = cv2.imread(image)13    h,w,_ = img.shape14    for y in range(0, h, patch_size):15        for x in range(0, w, patch_size):16            patch = img[y:y+patch_size, x:x+patch_size]17 18            19            patch_filename = f"patch_{y}_{x}.png" 20            patch_path = os.path.join(destination, patch_filename)21            cv2.imwrite(patch_path, patch)22 23def merge(patch_folder , dest_image = 'out.png', image_shape = None):24    merged = np.zeros(image_shape[:-1] + (3,), dtype=np.uint8)25    for filename in os.listdir(patch_folder):26        if filename.endswith(".png"):27            patch_path = os.path.join(patch_folder, filename)28            patch = cv2.imread(patch_path)29            patch_height, patch_width, _ = patch.shape30 31            # Extract patch coordinates from filename32            parts = filename.split("_")33            x, y = None, None34            for part in parts:35                if part.endswith(".png"):36                    x = int(part.split(".")[0])37                elif part.isdigit():38                    y = int(part)39            if x is None or y is None:40                raise ValueError(f"Invalid filename: {filename}")41 42            # Check if patch fits within image boundaries43            if x + patch_width > image_shape[1] or y + patch_height > image_shape[0]:44                # Adjust patch position to fit within image boundaries45                if x + patch_width > image_shape[1]:46                    x = image_shape[1] - patch_width47                if y + patch_height > image_shape[0]:48                    y = image_shape[0] - patch_height49 50            # Merge patch into the main image51            merged[y:y+patch_height, x:x+patch_width, :] = patch52 53    cv2.imwrite(dest_image, merged)