-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfind_blocks.py
80 lines (59 loc) · 2.66 KB
/
find_blocks.py
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
import os
import argparse
from functools import partial
from concurrent.futures import ProcessPoolExecutor
import cv2
import numpy as np
def find_and_draw_borders(input_image_path, output_image_path):
# Load image
image = cv2.imread(input_image_path)
if image is None:
raise FileNotFoundError("Specified image does not exist at the path.")
# To grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# List where the final outlines to be drawn will be stored
final_contours = []
for contour in contours:
# Calculate the bounding rectangle for the current path
x, y, w, h = cv2.boundingRect(contour)
current_rect = (x, y, x + w, y + h)
# Checking whether this contour is completely contained within another
is_contained = False
for other_contour in contours:
if np.array_equal(contour, other_contour):
continue # We skip comparing the contour with itself
ox, oy, ow, oh = cv2.boundingRect(other_contour)
other_rect = (ox, oy, ox + ow, oy + oh)
if (current_rect[0] >= other_rect[0] and current_rect[2] <= other_rect[2] and
current_rect[1] >= other_rect[1] and current_rect[3] <= other_rect[3]):
is_contained = True
break
if not is_contained:
final_contours.append(contour)
for contour in final_contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imwrite(output_image_path, image)
def process_proxy(image, src, dest):
src = os.path.join(src, image)
dest = os.path.join(dest, image)
find_and_draw_borders(src, dest)
def process_dir_images(source_dir, output_dir):
# Ensure the output directory exists
if not os.path.exists(output_dir):
os.makedirs(output_dir)
process = partial(process_proxy, src=source_dir, dest=output_dir)
images = os.listdir(source_dir)
with ProcessPoolExecutor(max_workers=os.cpu_count()) as pool:
res = pool.map(process, images)
list(res)
def main():
parser = argparse.ArgumentParser(description="Find blocks contours")
parser.add_argument('--source_dir', type=str, required=True, help="Directory containing images")
parser.add_argument('--output_dir', type=str, required=True, help="Directory to save the images")
args = parser.parse_args()
process_dir_images(args.source_dir, args.output_dir)
if __name__ == "__main__":
main()