Pavan2k4 commited on
Commit
2d4af4b
·
verified ·
1 Parent(s): 5debfe9

Create split_merge.py

Browse files
Files changed (1) hide show
  1. split_merge.py +53 -0
split_merge.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import numpy as np
4
+
5
+ patches_folder = "Patches/"
6
+ pred_patches = "Patch_pred/"
7
+ os.makedirs(patches_folder, exist_ok=True)
8
+ os.makedirs(pred_patches,exist_ok=True)
9
+
10
+
11
+ def split(image, destination = patches_folder, patch_size = 256):
12
+ img = cv2.imread(image)
13
+ h,w,_ = img.shape
14
+ 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
+
23
+ def 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.shape
30
+
31
+ # Extract patch coordinates from filename
32
+ parts = filename.split("_")
33
+ x, y = None, None
34
+ 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 boundaries
43
+ if x + patch_width > image_shape[1] or y + patch_height > image_shape[0]:
44
+ # Adjust patch position to fit within image boundaries
45
+ if x + patch_width > image_shape[1]:
46
+ x = image_shape[1] - patch_width
47
+ if y + patch_height > image_shape[0]:
48
+ y = image_shape[0] - patch_height
49
+
50
+ # Merge patch into the main image
51
+ merged[y:y+patch_height, x:x+patch_width, :] = patch
52
+
53
+ cv2.imwrite(dest_image, merged)