feat: implement 4-way cardinal rotation OCR perception with fine-text sensitivity and spatial deduplication

This commit is contained in:
Abhinav Gupta
2026-09-27 22:32:11 +05:30
parent 57e0d98812
commit beb35af2ec
3 changed files with 149 additions and 79 deletions
+96 -54
View File
@@ -151,8 +151,14 @@ def _get_easyocr():
def _run_easyocr(image_path: str, img_w: int, img_h: int) -> List[Dict[str, Any]]:
"""
Run EasyOCR on loaded image with dual-angle perception (0° horizontal + 90° vertical)
to ensure full capture of vertical piping lines and valve tags.
Run EasyOCR on loaded image with 4-direction cardinal perception:
- 0°: Standard horizontal text (left-to-right)
- 90°: Vertical text CW (top-to-bottom lines & valves)
- 180°: Inverted horizontal text (bottom-mounted tags & reverse lines)
- 270°: Vertical text CCW (bottom-to-top lines & margins)
Captures smallest fine text (min_size=3, text_threshold=0.30, low_text=0.20),
inverts rotated coordinates back to original image space, and deduplicates spatially.
"""
reader = _get_easyocr()
import cv2
@@ -162,45 +168,33 @@ def _run_easyocr(image_path: str, img_w: int, img_h: int) -> List[Dict[str, Any]
H, W = img_cv.shape[:2]
# Pass 1: Horizontal text (0°)
raw_h = reader.readtext(img_cv, detail=1, paragraph=False,
min_size=5, text_threshold=0.4, low_text=0.25,
decoder='greedy', workers=0)
items = []
seen_texts = set()
# Cardinal orientation matrices
rotations = {
0: img_cv,
90: cv2.rotate(img_cv, cv2.ROTATE_90_CLOCKWISE),
180: cv2.rotate(img_cv, cv2.ROTATE_180),
270: cv2.rotate(img_cv, cv2.ROTATE_90_COUNTERCLOCKWISE),
}
for res in raw_h:
if len(res) == 3:
bbox, text, conf = res
elif len(res) == 2:
bbox, text = res
conf = 0.90
else:
continue
all_raw_items = []
clean_text = text.strip()
if not clean_text or float(conf) < 0.15:
continue
xs = [pt[0] for pt in bbox]
ys = [pt[1] for pt in bbox]
center_x = round((sum(xs) / len(xs)) / max(W, 1), 4)
center_y = round((sum(ys) / len(ys)) / max(H, 1), 4)
items.append({
"text": clean_text,
"confidence": round(float(conf), 3),
"bbox": bbox,
"center_x": center_x,
"center_y": center_y,
})
seen_texts.add(clean_text)
# Pass 2: Vertical text (90° clockwise rotation)
for angle, rot_img in rotations.items():
try:
img_cw = cv2.rotate(img_cv, cv2.ROTATE_90_CLOCKWISE)
raw_cw = reader.readtext(img_cw, detail=1, paragraph=False,
min_size=5, text_threshold=0.4, low_text=0.25,
decoder='greedy', workers=0)
for res in raw_cw:
# High-sensitivity OCR parameters to catch fine, small, and faint text
raw = reader.readtext(
rot_img,
detail=1,
paragraph=False,
min_size=3,
text_threshold=0.30,
low_text=0.20,
link_threshold=0.30,
canvas_size=2560,
decoder='greedy',
workers=0
)
for res in raw:
if len(res) == 3:
bbox_rot, text, conf = res
elif len(res) == 2:
@@ -210,36 +204,84 @@ def _run_easyocr(image_path: str, img_w: int, img_h: int) -> List[Dict[str, Any]
continue
clean_text = text.strip()
if not clean_text or float(conf) < 0.20:
if not clean_text or float(conf) < 0.15:
continue
# Map coordinates from 90° CW rotated space back to original image space
# Rotated (xr, yr) -> Original (yr, H - 1 - xr)
# Filter single-character noise on rotated passes unless numeric or valid single-letter tag
if angle != 0 and len(clean_text) < 2 and not clean_text.isdigit() and clean_text.upper() not in {'V', 'P', 'E', 'T', 'F', 'L'}:
continue
# Invert rotated coordinates back into original image coordinate space
if angle == 0:
orig_bbox = [[float(pt[0]), float(pt[1])] for pt in bbox_rot]
elif angle == 90:
# 90° CW: (xr, yr) -> (yr, H - 1 - xr)
orig_bbox = [[float(pt[1]), float(H - 1 - pt[0])] for pt in bbox_rot]
elif angle == 180:
# 180°: (xr, yr) -> (W - 1 - xr, H - 1 - yr)
orig_bbox = [[float(W - 1 - pt[0]), float(H - 1 - pt[1])] for pt in bbox_rot]
elif angle == 270:
# 270° CCW: (xr, yr) -> (W - 1 - yr, xr)
orig_bbox = [[float(W - 1 - pt[1]), float(pt[0])] for pt in bbox_rot]
xs = [pt[0] for pt in orig_bbox]
ys = [pt[1] for pt in orig_bbox]
center_x = round((sum(xs) / len(xs)) / max(W, 1), 4)
center_y = round((sum(ys) / len(ys)) / max(H, 1), 4)
# Avoid exact duplicate text at the same spatial coordinates
is_dup = False
if clean_text in seen_texts:
for existing in items:
if existing["text"] == clean_text and abs(existing["center_x"] - center_x) < 0.03 and abs(existing["center_y"] - center_y) < 0.03:
is_dup = True
break
if not is_dup:
items.append({
all_raw_items.append({
"text": clean_text,
"confidence": round(float(conf), 3),
"bbox": orig_bbox,
"center_x": center_x,
"center_y": center_y,
"angle": angle,
})
seen_texts.add(clean_text)
except Exception as rot_err:
logger.warning(f"Vertical OCR pass warning: {rot_err}")
except Exception as scan_err:
logger.warning(f"EasyOCR angle {angle}° scan warning: {scan_err}")
return items
# ── Spatial Deduplication & Merging Across Angles ──────────────────────────
# If two detections are at virtually the same spot (dx < 0.02, dy < 0.02):
# - If text matches (or case-insensitive equal), keep highest confidence.
# - If one contains an engineering tag format, prefer the tag.
merged_items: List[Dict[str, Any]] = []
for item in all_raw_items:
t = item["text"]
cx = item["center_x"]
cy = item["center_y"]
conf = item["confidence"]
matched_idx = None
for idx, existing in enumerate(merged_items):
ecx = existing["center_x"]
ecy = existing["center_y"]
if abs(cx - ecx) < 0.020 and abs(cy - ecy) < 0.020:
et = existing["text"]
# Exact or case-insensitive match
if t.upper() == et.upper():
matched_idx = idx
break
# Substring match (e.g. '4"-TA-4424' vs 'TA-4424')
if t.upper() in et.upper() or et.upper() in t.upper():
matched_idx = idx
break
if matched_idx is not None:
existing = merged_items[matched_idx]
et = existing["text"]
econf = existing["confidence"]
# Prefer longer tag or higher confidence if same length
if len(t) > len(et) or (len(t) == len(et) and conf > econf):
merged_items[matched_idx] = item
else:
merged_items.append(item)
logger.info(
f"EasyOCR 4-way perception: {len(all_raw_items)} raw items across 4 angles "
f"-> {len(merged_items)} deduplicated text items."
)
return merged_items
# ──────────────────────────────────────────────────────────────────────────────
+14 -5
View File
@@ -152,7 +152,7 @@ _ISA_SAFE_CODES = [
]
_ISA_SAFE_CODES_JOINED = '|'.join(_ISA_SAFE_CODES)
_BARE_INSTRUMENT_SEARCH = re.compile(
rf'\b((?:{_ISA_SAFE_CODES_JOINED})-\d{{3,5}}[A-Z]?)\b', # hyphen required, 3+ digits
rf'\b((?:{_ISA_SAFE_CODES_JOINED})[-–]\d{{1,5}}(?:[/-][\dA-Z]{{1,5}})?[A-Z]?)\b',
re.IGNORECASE
)
@@ -173,14 +173,19 @@ _SERVICE_CODE_PATTERN = re.compile(
# Separated: 26-CB-9131A, 26-GB-9178
# Named control valves: HV-101, XV-201, FV-9076, PCV-9044, SDV-201
# Block valves: BV-101, NV-201, GV-101, BFV-201
# Synthetic / Vendor prefixes: QR-70427, GH-83714, KL-21519, EF-96470, ST-93705, CS-97
# Synthetic / Vendor prefixes: QR-70427, GH-83714, KL-21519, EF-96470, ST-93705, CS-97, WV-70609, DV-07707
_KNOWN_VALVE_PREFIXES = {
'HV', 'XV', 'CV', 'PCV', 'FCV', 'TCV', 'LCV', 'MOV', 'SDV', 'BDV', 'FV', 'UV', 'TV',
'LV', 'AV', 'ZV', 'RV', 'SV', 'DV', 'WV', 'MV', 'BV', 'NV', 'GV', 'BFV', 'PLV',
'QR', 'GH', 'KL', 'EF', 'ST', 'CS'
}
_VALVE_SEARCH = re.compile(
r'\b('
r'\d{2}-?[A-Z]{2}-?\d{4,6}[A-Z]?' # 26CB9131, 26-CB-9131A
r'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV|RV|SV)[-–]\d{2,6}[A-Z]?' # HV-101, SDV-201
r'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV|RV|SV|DV|WV|MV)[-–]\d{2,6}[A-Z]?' # HV-101, SDV-201
r'|(?:BV|NV|GV|BFV|SBV|NGV|PLV|PRV)[-–]\d{2,6}[A-Z]?' # BV-101, NV-201
r'|(?:QR|GH|KL|EF|ST|CS)[-–]\d{2,6}[A-Z]?' # Synthetic P&ID valve tags
r'|\bV-\d{3,5}[A-Z]?' # V-101
r'|(?:QR|GH|KL|EF|ST|CS|WV|DV|RV|AV|CV|UV)[-–]\d{2,6}[A-Z]?' # Synthetic P&ID valve tags
r'|\bV-\d{2,5}[A-Z]?' # V-101, V-700
r'|(?:(?:LOADING|SUCTION|PURGE|VENT|DISCHARGE|RECYCLE|BYPASS|RELIEF|BLOWDOWN|CHECK|MAINLINE(?:\s+BLOCK)?)\s+VALVE)' # Schematic valve callouts
r')\b',
re.IGNORECASE
@@ -602,6 +607,10 @@ def classify_paddle_results(
if len(parts) >= 3 and parts[0].isdigit() and len(parts[0]) == 2 and not has_explicit_size:
if parts[1] in (_EQUIP_PREFIX_ALLOWLIST | _EQUIPMENT_CODES):
continue
# Guard against valve tags being misclassified as lines (e.g. 29"-EF-96470, EF-96470)
svc_code = parts[1] if has_explicit_size and len(parts) >= 2 else parts[0]
if svc_code in _KNOWN_VALVE_PREFIXES:
continue
flag_reason = None
tag_conf = conf
+25 -6
View File
@@ -35,9 +35,14 @@ _CORE_LINE_TAG_PATTERN = re.compile(
re.IGNORECASE
)
# Valve prefix fragments (e.g., HV, XV, 26-GB, 26CB)
# Valve prefix fragments (e.g., HV, XV, 26-GB, 26CB, EF, QR, GH, KL, ST, CS)
_KNOWN_VALVE_PREFIXES = {
'HV', 'XV', 'CV', 'PCV', 'FCV', 'TCV', 'LCV', 'MOV', 'SDV', 'BDV', 'FV', 'UV', 'TV',
'LV', 'AV', 'ZV', 'RV', 'SV', 'DV', 'WV', 'MV', 'BV', 'NV', 'GV', 'BFV', 'PLV',
'QR', 'GH', 'KL', 'EF', 'ST', 'CS'
}
_VALVE_PREFIX_PATTERN = re.compile(
r'^(?:\d{2}-?)?(?:HV|XV|CV|PCV|FCV|TCV|LCV|MOV|SDV|BDV|GB|CB|BV|NV|GV|BFV|PLV|V)[-–]?$',
r'^(?:\d{2}-?)?(?:HV|XV|CV|PCV|FCV|TCV|LCV|MOV|SDV|BDV|GB|CB|BV|NV|GV|BFV|PLV|QR|GH|KL|EF|ST|CS|V)[-–]?$',
re.IGNORECASE
)
@@ -59,6 +64,10 @@ def rectify_ocr_typos(text: str) -> str:
cleaned = re.sub(r'\bl/2"', '1/2"', cleaned)
cleaned = re.sub(r'\b3I4"', '3/4"', cleaned)
cleaned = re.sub(r'\bI"', '1"', cleaned)
# Fix stray tick stroke before single-digit pipe sizes (e.g. 74" -> 4", 73" -> 3")
cleaned = re.sub(r'\b7([23468]")', r'\1', cleaned)
# Insert missing hyphen between pipe size and letter code (e.g. 4"TA-4424 -> 4"-TA-4424)
cleaned = re.sub(r'(\d+(?:[/\.]\d+)?(?:["\']|mm|DN))([A-Z])', r'\1-\2', cleaned)
# 3. Fix en-dashes / em-dashes / long underscores to standard hyphen
cleaned = re.sub(r'[–—_]+', '-', cleaned)
@@ -186,19 +195,24 @@ def stitch_fragmented_tags(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
if _PIPE_SIZE_PATTERN.match(text_i):
# Look for adjacent core line tag to the right or below
matched_j = None
best_dist = 999.0
best_dist = 0.09 # Strictly adjacent tokens only (not distant drawing elements)
for j in range(n):
if i == j or j in merged_indices:
continue
item_j = processed_items[j]
text_j = item_j.get("text", "").strip()
# Exclude valve tags from being falsely stitched as line cores
code_m = re.match(r'^([A-Z]{2,4})[-–]', text_j, re.IGNORECASE)
if code_m and code_m.group(1).upper() in _KNOWN_VALVE_PREFIXES:
continue
cx_j, cy_j, w_j, h_j, xmin_j, xmax_j = _get_item_box(item_j)
# Same horizontal line (cy close) and j is to the right of i
is_horiz = abs(cy_i - cy_j) < max(0.025, h_i * 1.2) and (0 <= (cx_j - cx_i) < 0.25)
is_horiz = abs(cy_i - cy_j) < max(0.025, h_i * 1.2) and (0 <= (cx_j - cx_i) < 0.08)
# Or same vertical column (cx close) and j is below i
is_vert = abs(cx_i - cx_j) < max(0.025, w_i * 1.2) and (0 <= (cy_j - cy_i) < 0.20)
is_vert = abs(cx_i - cx_j) < max(0.025, w_i * 1.2) and (0 <= (cy_j - cy_i) < 0.08)
if (is_horiz or is_vert) and _CORE_LINE_TAG_PATTERN.search(text_j):
dist = math.hypot(cx_j - cx_i, cy_j - cy_i)
@@ -226,8 +240,13 @@ def stitch_fragmented_tags(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
continue
item_k = processed_items[k]
text_k = item_k.get("text", "").strip()
# Do not stitch valve tags as trailing specs
code_k = re.match(r'^([A-Z]{2,4})[-–]', text_k, re.IGNORECASE)
if code_k and code_k.group(1).upper() in _KNOWN_VALVE_PREFIXES:
continue
cx_k, cy_k, _, _, _, _ = _get_item_box(item_k)
if abs(cy_m - cy_k) < 0.025 and (0 <= (cx_k - cx_m) < 0.20) and _SPEC_OR_INSULATION_PATTERN.match(text_k):
if abs(cy_m - cy_k) < 0.025 and (0 <= (cx_k - cx_m) < 0.08) and _SPEC_OR_INSULATION_PATTERN.match(text_k):
combined_tag = f"{combined_tag}-{text_k}".replace('--', '-')
merged_item["text"] = combined_tag
merged_item["value"] = combined_tag