floorplan-analyzer / utils /extractor.py
MrDasOfficial's picture
Update utils/extractor.py
470db6f verified
Raw History Blame Contribute Delete
5.44 kB
import easyocr
from rapidfuzz import fuzz
import cv2
from ultralytics import YOLO
import numpy as np
class TextDetector:
def __init__(self, gpu=True):
self.reader = easyocr.Reader(['en'], gpu=gpu)
def extract_and_search(self, processed_text_img, query):
results = self.reader.readtext(
processed_text_img,
rotation_info=[90, 180, 270],
mag_ratio=2.0,
text_threshold=0.3,
low_text=0.2,
paragraph=False
)
search_query = query.upper().strip()
output_img = processed_text_img.copy()
match_count = 0
for (bbox, text, prob) in results:
detected_text = text.upper().strip()
if fuzz.partial_ratio(search_query, detected_text) >= 70:
match_count += 1
pts = np.array(bbox, np.int32)
cv2.polylines(
output_img,
[pts],
True,
(255, 0, 0),
4
)
# TOP CENTER TEXT
result_text = f"Matches Found: {match_count}"
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 2
thickness = 2
text_size = cv2.getTextSize(result_text,font,font_scale,thickness)[0]
text_x = (output_img.shape[1] - text_size[0]) // 2
text_y = 50
# background rectangle
cv2.rectangle(output_img,(text_x - 10, text_y - 35),
(text_x + text_size[0] + 10, text_y + 10),(0, 0, 0),-1)
# text
cv2.putText(output_img,result_text,(text_x, text_y),
font,font_scale,(255, 255, 255),thickness)
return output_img
class DoorDetector:
def __init__(
self,
model_path = "door_detector_model/weights/best.pt",
tile_size=256,
stride=128):
self.model = YOLO(model_path)
self.tile_size = tile_size
self.stride = stride
def predict(
self,
image_path,
confidence_threshold=0.7,
output_path="door_detection_output.png"):
# load image
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(
f"Unable to load image: {image_path}"
)
original_img = img.copy()
H, W = img.shape[:2]
all_boxes = []
# tiled inference
for y in range(0, H, self.stride):
for x in range(0, W, self.stride):
x2 = min(x + self.tile_size, W)
y2 = min(y + self.tile_size, H)
tile = img[y:y2, x:x2]
# skip tiny edge tiles
if tile.shape[0] < 100 or tile.shape[1] < 100:
continue
results = self.model.predict(source=tile,imgsz=self.tile_size,
conf=confidence_threshold,verbose=False)
result = results[0]
boxes = result.boxes
for box in boxes:
bx1, by1, bx2, by2 = map(
int,
box.xyxy[0]
)
confidence = float(box.conf[0])
# convert to global coords
gx1 = bx1 + x
gy1 = by1 + y
gx2 = bx2 + x
gy2 = by2 + y
all_boxes.append([
gx1,
gy1,
gx2,
gy2,
confidence
])
# non-max suppression
final_boxes = []
if len(all_boxes) > 0:
boxes_xywh = []
confidences = []
for b in all_boxes:
x1, y1, x2, y2, conf = b
boxes_xywh.append([
int(x1),
int(y1),
int(x2 - x1),
int(y2 - y1)
])
confidences.append(float(conf))
indices = cv2.dnn.NMSBoxes(
boxes_xywh,
confidences,
score_threshold=confidence_threshold,
nms_threshold=0.30
)
if len(indices) > 0:
for i in indices.flatten():
final_boxes.append(all_boxes[i])
# draw detections
for box in final_boxes:
x1, y1, x2, y2, conf = box
cv2.rectangle(
original_img,
(int(x1), int(y1)),
(int(x2), int(y2)),
(0, 255, 0),
2
)
# total count
door_count = len(final_boxes)
count_text = f"Total Doors: {door_count}"
text_x = original_img.shape[1] - 350
text_y = 50
cv2.rectangle(original_img,(text_x - 10, text_y - 35),
(text_x + 320, text_y + 10),(0, 0, 0),-1)
cv2.putText(original_img,count_text,(text_x, text_y),
cv2.FONT_HERSHEY_SIMPLEX,1,(255, 255, 255),2)
# save output
cv2.imwrite(output_path, original_img)
return {
"door_count": door_count,
"detections": final_boxes,
"output_path": output_path,
"output_image": original_img
}