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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
import glob
|
5 |
+
import argparse
|
6 |
+
import datetime
|
7 |
+
import shutil
|
8 |
+
import numpy as np
|
9 |
+
import cv2
|
10 |
+
from PIL import Image
|
11 |
+
from ultralytics import YOLO
|
12 |
+
from huggingface_hub import hf_hub_download
|
13 |
+
|
14 |
+
# XML generation imports
|
15 |
+
import xml.etree.ElementTree as ET
|
16 |
+
from xml.dom import minidom
|
17 |
+
|
18 |
+
# Define models
|
19 |
+
MODEL_OPTIONS = {
|
20 |
+
"YOLOv11-Nano": "yolov11n-seg.pt",
|
21 |
+
"YOLOv11-Small": "yolov11s-seg.pt",
|
22 |
+
"YOLOv11-Medium": "yolov11m-seg.pt",
|
23 |
+
"YOLOv11-Large": "yolov11l-seg.pt",
|
24 |
+
"YOLOv11-XLarge": "yolov11x-seg.pt"
|
25 |
+
}
|
26 |
+
|
27 |
+
# Dictionary to store loaded models
|
28 |
+
models: Dict[str, YOLO] = {}
|
29 |
+
|
30 |
+
# Load specified model or default to Nano
|
31 |
+
def load_model(model_name: str = "YOLOv11-Nano") -> YOLO:
|
32 |
+
if model_name not in models:
|
33 |
+
model_file = MODEL_OPTIONS[model_name]
|
34 |
+
model_path = hf_hub_download(
|
35 |
+
repo_id="wjbmattingly/kraken-yiddish",
|
36 |
+
filename=model_file
|
37 |
+
)
|
38 |
+
models[model_name] = YOLO(model_path)
|
39 |
+
return models[model_name]
|
40 |
+
|
41 |
+
def process_image(
|
42 |
+
image_path: str,
|
43 |
+
model_name: str = "YOLOv11-Medium",
|
44 |
+
conf_threshold: float = 0.25,
|
45 |
+
iou_threshold: float = 0.45
|
46 |
+
) -> tuple:
|
47 |
+
"""Process an image and return detection results and annotated image"""
|
48 |
+
|
49 |
+
# Read the image
|
50 |
+
image = cv2.imread(image_path)
|
51 |
+
if image is None:
|
52 |
+
raise ValueError(f"Cannot read image: {image_path}")
|
53 |
+
|
54 |
+
# Convert BGR to RGB for YOLO
|
55 |
+
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
56 |
+
|
57 |
+
# Get image dimensions
|
58 |
+
height, width = image.shape[:2]
|
59 |
+
|
60 |
+
# Get the selected model
|
61 |
+
model = load_model(model_name)
|
62 |
+
|
63 |
+
# Perform inference with YOLO
|
64 |
+
results = model(
|
65 |
+
image_rgb,
|
66 |
+
conf=conf_threshold,
|
67 |
+
iou=iou_threshold,
|
68 |
+
verbose=False,
|
69 |
+
device='cpu'
|
70 |
+
)
|
71 |
+
|
72 |
+
# Get the first result
|
73 |
+
result = results[0]
|
74 |
+
|
75 |
+
# Create annotated image for visualization
|
76 |
+
annotated_image = result.plot(
|
77 |
+
conf=True,
|
78 |
+
line_width=None,
|
79 |
+
font_size=None,
|
80 |
+
boxes=True,
|
81 |
+
masks=True,
|
82 |
+
probs=True,
|
83 |
+
labels=True
|
84 |
+
)
|
85 |
+
|
86 |
+
# Convert back to BGR for saving with OpenCV
|
87 |
+
annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)
|
88 |
+
|
89 |
+
return result, annotated_image, width, height
|
90 |
+
|
91 |
+
def create_page_xml(
|
92 |
+
image_filename: str,
|
93 |
+
result,
|
94 |
+
width: int,
|
95 |
+
height: int
|
96 |
+
) -> str:
|
97 |
+
"""Create PAGE XML structure from YOLO results"""
|
98 |
+
|
99 |
+
# Create the root element
|
100 |
+
root = ET.Element("PcGts", {
|
101 |
+
"xmlns": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15",
|
102 |
+
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
|
103 |
+
"xsi:schemaLocation": "http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15 http://schema.primaresearch.org/PAGE/gts/pagecontent/2019-07-15/pagecontent.xsd"
|
104 |
+
})
|
105 |
+
|
106 |
+
# Add metadata
|
107 |
+
metadata = ET.SubElement(root, "Metadata")
|
108 |
+
ET.SubElement(metadata, "Creator").text = "escriptorium"
|
109 |
+
|
110 |
+
# Use a future date like in the example
|
111 |
+
future_date = (datetime.datetime.now() + datetime.timedelta(days=365)).isoformat()
|
112 |
+
ET.SubElement(metadata, "Created").text = future_date
|
113 |
+
ET.SubElement(metadata, "LastChange").text = future_date
|
114 |
+
|
115 |
+
# Add page element with original image filename
|
116 |
+
page = ET.SubElement(root, "Page", {
|
117 |
+
"imageFilename": os.path.basename(image_filename),
|
118 |
+
"imageWidth": str(width),
|
119 |
+
"imageHeight": str(height)
|
120 |
+
})
|
121 |
+
|
122 |
+
# Process each detected mask/contour as a separate TextRegion
|
123 |
+
has_valid_masks = False
|
124 |
+
|
125 |
+
if hasattr(result, 'masks') and result.masks is not None:
|
126 |
+
masks = result.masks.xy
|
127 |
+
|
128 |
+
# Create main text region for the right side (assuming right-to-left Hebrew/Yiddish text)
|
129 |
+
# Use a unique timestamp for the ID
|
130 |
+
timestamp = int(datetime.datetime.now().timestamp())
|
131 |
+
main_region_id = f"eSc_textblock_TextRegion_{timestamp}"
|
132 |
+
|
133 |
+
# Get bounding box of all masks to determine the text region
|
134 |
+
all_points_x = []
|
135 |
+
all_points_y = []
|
136 |
+
valid_masks = []
|
137 |
+
|
138 |
+
# First pass: filter all masks and collect valid points
|
139 |
+
for mask_points in masks:
|
140 |
+
# Filter out NaN values from mask points
|
141 |
+
valid_points = [(p[0], p[1]) for p in mask_points if not (np.isnan(p[0]) or np.isnan(p[1]))]
|
142 |
+
|
143 |
+
if valid_points and len(valid_points) >= 3: # Only proceed if we have enough valid points
|
144 |
+
valid_masks.append(valid_points)
|
145 |
+
all_points_x.extend([p[0] for p in valid_points])
|
146 |
+
all_points_y.extend([p[1] for p in valid_points])
|
147 |
+
has_valid_masks = True
|
148 |
+
|
149 |
+
# Calculate the text region coordinates if we have valid points
|
150 |
+
if has_valid_masks and all_points_x and all_points_y:
|
151 |
+
min_x = max(0, int(min(all_points_x)))
|
152 |
+
max_x = min(width, int(max(all_points_x)))
|
153 |
+
min_y = max(0, int(min(all_points_y)))
|
154 |
+
max_y = min(height, int(max(all_points_y)))
|
155 |
+
|
156 |
+
# Create main text region with calculated bounds
|
157 |
+
main_text_region = ET.SubElement(page, "TextRegion", {
|
158 |
+
"id": main_region_id,
|
159 |
+
"custom": "structure {type:text_zone;}"
|
160 |
+
})
|
161 |
+
|
162 |
+
# Add coordinates for the text region (use rectangle format)
|
163 |
+
region_points = f"{min_x},{min_y} {max_x},{min_y} {max_x},{max_y} {min_x},{max_y}"
|
164 |
+
ET.SubElement(main_text_region, "Coords", {"points": region_points})
|
165 |
+
|
166 |
+
# Process each valid mask
|
167 |
+
for i, valid_points in enumerate(valid_masks):
|
168 |
+
# Create text line with auto-incrementing ID
|
169 |
+
line_id = f"eSc_line_r2l{i+1}" if i > 0 else "eSc_line_line_1610719743362_3154"
|
170 |
+
text_line = ET.SubElement(main_text_region, "TextLine", {
|
171 |
+
"id": line_id,
|
172 |
+
"custom": "structure {type:text_line;}"
|
173 |
+
})
|
174 |
+
|
175 |
+
# Format mask points for PAGE XML format
|
176 |
+
# Convert to int to avoid scientific notation
|
177 |
+
points_str = " ".join([f"{int(p[0])},{int(p[1])}" for p in valid_points])
|
178 |
+
|
179 |
+
# Add coordinates to the text line
|
180 |
+
line_coords = ET.SubElement(text_line, "Coords", {
|
181 |
+
"points": points_str
|
182 |
+
})
|
183 |
+
|
184 |
+
# Calculate baseline points spanning the entire width of the polygon
|
185 |
+
# Sort points by x-value to find the left and right boundaries
|
186 |
+
points_by_x = sorted(valid_points, key=lambda p: p[0])
|
187 |
+
leftmost_point = points_by_x[0]
|
188 |
+
rightmost_point = points_by_x[-1]
|
189 |
+
|
190 |
+
# Sort points by y-value (ascending) to find the bottom area of the line
|
191 |
+
sorted_by_y = sorted(valid_points, key=lambda p: p[1])
|
192 |
+
|
193 |
+
# Take points in the bottom third, but ensure we have at least one point
|
194 |
+
bottom_third_index = max(0, int(len(sorted_by_y) * 0.67))
|
195 |
+
bottom_points = sorted_by_y[bottom_third_index:]
|
196 |
+
|
197 |
+
if not bottom_points: # Fallback if no bottom points
|
198 |
+
bottom_points = sorted_by_y # Use all points
|
199 |
+
|
200 |
+
# Find the average y-value of bottom points for a straight baseline
|
201 |
+
avg_y = sum(p[1] for p in bottom_points) / len(bottom_points)
|
202 |
+
|
203 |
+
# Create baseline with two points spanning the full width
|
204 |
+
left_x = leftmost_point[0]
|
205 |
+
right_x = rightmost_point[0]
|
206 |
+
|
207 |
+
# Create baseline string with exactly two points
|
208 |
+
baseline_str = f"{int(left_x)},{int(avg_y)} {int(right_x)},{int(avg_y)}"
|
209 |
+
|
210 |
+
# Add baseline
|
211 |
+
baseline = ET.SubElement(text_line, "Baseline", {
|
212 |
+
"points": baseline_str
|
213 |
+
})
|
214 |
+
|
215 |
+
# Add empty text equivalent
|
216 |
+
text_equiv = ET.SubElement(text_line, "TextEquiv")
|
217 |
+
ET.SubElement(text_equiv, "Unicode")
|
218 |
+
|
219 |
+
# Create a second text region for the left side
|
220 |
+
# This is to mimic the structure in the example but with empty content
|
221 |
+
left_region = ET.SubElement(page, "TextRegion", {
|
222 |
+
"id": f"eSc_textblock_r1",
|
223 |
+
"custom": "structure {type:text_zone;}"
|
224 |
+
})
|
225 |
+
|
226 |
+
# Left region takes up the left side of the page
|
227 |
+
left_region_points = f"0,0 {min_x-10},{min_y} {min_x-10},{max_y} 0,{max_y}"
|
228 |
+
ET.SubElement(left_region, "Coords", {"points": left_region_points})
|
229 |
+
|
230 |
+
# If no valid masks were found, create a default text region covering the whole page
|
231 |
+
if not has_valid_masks:
|
232 |
+
print("Warning: No valid masks detected. Creating a default text region.")
|
233 |
+
default_region = ET.SubElement(page, "TextRegion", {
|
234 |
+
"id": f"eSc_textblock_default_{int(datetime.datetime.now().timestamp())}",
|
235 |
+
"custom": "structure {type:text_zone;}"
|
236 |
+
})
|
237 |
+
default_points = f"0,0 {width},0 {width},{height} 0,{height}"
|
238 |
+
ET.SubElement(default_region, "Coords", {"points": default_points})
|
239 |
+
|
240 |
+
# Convert to string with pretty formatting
|
241 |
+
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
|
242 |
+
|
243 |
+
return xmlstr
|
244 |
+
|
245 |
+
def save_results(image_path: str, annotated_image: np.ndarray, xml_content: str):
|
246 |
+
"""Save the original image to output/ and XML file to annotations/ directory"""
|
247 |
+
|
248 |
+
# Create output and annotations directories if they don't exist
|
249 |
+
output_dir = "output"
|
250 |
+
annotations_dir = "annotations"
|
251 |
+
os.makedirs(output_dir, exist_ok=True)
|
252 |
+
os.makedirs(annotations_dir, exist_ok=True)
|
253 |
+
|
254 |
+
# Get the base filename without extension
|
255 |
+
base_name = os.path.basename(image_path)
|
256 |
+
file_name_no_ext = os.path.splitext(base_name)[0]
|
257 |
+
|
258 |
+
# Copy the original image to output directory
|
259 |
+
output_image_path = os.path.join(output_dir, f"{file_name_no_ext}.jpg")
|
260 |
+
# Use shutil.copy to directly copy the file instead of reading/writing
|
261 |
+
shutil.copy(image_path, output_image_path)
|
262 |
+
|
263 |
+
# Save the XML file to annotations directory
|
264 |
+
output_xml_path = os.path.join(annotations_dir, f"{file_name_no_ext}.xml")
|
265 |
+
with open(output_xml_path, "w", encoding="utf-8") as f:
|
266 |
+
f.write(xml_content)
|
267 |
+
|
268 |
+
print(f"Results saved to:")
|
269 |
+
print(f" Image: {output_image_path}")
|
270 |
+
print(f" XML: {output_xml_path}")
|
271 |
+
|
272 |
+
def main():
|
273 |
+
parser = argparse.ArgumentParser(description="Convert YOLO segmentation to PAGE XML format")
|
274 |
+
parser.add_argument("image_path", help="Path to the input image or directory of images")
|
275 |
+
parser.add_argument("--model", default="YOLOv11-Medium", choices=MODEL_OPTIONS.keys(),
|
276 |
+
help="Model to use for detection")
|
277 |
+
parser.add_argument("--conf", type=float, default=0.25,
|
278 |
+
help="Confidence threshold for detection")
|
279 |
+
parser.add_argument("--iou", type=float, default=0.45,
|
280 |
+
help="IoU threshold for detection")
|
281 |
+
parser.add_argument("--batch", action="store_true",
|
282 |
+
help="Process all images in the directory if image_path is a directory")
|
283 |
+
|
284 |
+
args = parser.parse_args()
|
285 |
+
|
286 |
+
# Check if the path is a directory and batch mode is enabled
|
287 |
+
if os.path.isdir(args.image_path) and args.batch:
|
288 |
+
# Get all image files in the directory
|
289 |
+
image_files = []
|
290 |
+
for extension in ['.jpg', '.jpeg', '.png', '.tif', '.tiff']:
|
291 |
+
image_files.extend(glob.glob(os.path.join(args.image_path, f"*{extension}")))
|
292 |
+
image_files.extend(glob.glob(os.path.join(args.image_path, f"*{extension.upper()}")))
|
293 |
+
|
294 |
+
if not image_files:
|
295 |
+
print(f"No image files found in directory: {args.image_path}")
|
296 |
+
sys.exit(1)
|
297 |
+
|
298 |
+
print(f"Found {len(image_files)} images to process")
|
299 |
+
|
300 |
+
# Process each image
|
301 |
+
for i, image_path in enumerate(image_files):
|
302 |
+
print(f"Processing {i+1}/{len(image_files)}: {os.path.basename(image_path)}")
|
303 |
+
try:
|
304 |
+
# Process the image
|
305 |
+
result, annotated_image, width, height = process_image(
|
306 |
+
image_path,
|
307 |
+
args.model,
|
308 |
+
args.conf,
|
309 |
+
args.iou
|
310 |
+
)
|
311 |
+
|
312 |
+
# Create PAGE XML
|
313 |
+
xml_content = create_page_xml(image_path, result, width, height)
|
314 |
+
|
315 |
+
# Save results
|
316 |
+
save_results(image_path, annotated_image, xml_content)
|
317 |
+
|
318 |
+
except Exception as e:
|
319 |
+
print(f"Error processing {image_path}: {e}")
|
320 |
+
import traceback
|
321 |
+
traceback.print_exc()
|
322 |
+
else:
|
323 |
+
# Process a single image
|
324 |
+
try:
|
325 |
+
# Process the image
|
326 |
+
result, annotated_image, width, height = process_image(
|
327 |
+
args.image_path,
|
328 |
+
args.model,
|
329 |
+
args.conf,
|
330 |
+
args.iou
|
331 |
+
)
|
332 |
+
|
333 |
+
# Create PAGE XML
|
334 |
+
xml_content = create_page_xml(args.image_path, result, width, height)
|
335 |
+
|
336 |
+
# Save results
|
337 |
+
save_results(args.image_path, annotated_image, xml_content)
|
338 |
+
|
339 |
+
except Exception as e:
|
340 |
+
print(f"Error: {e}")
|
341 |
+
import traceback
|
342 |
+
traceback.print_exc()
|
343 |
+
sys.exit(1)
|
344 |
+
|
345 |
+
if __name__ == "__main__":
|
346 |
+
main()
|