Skip to content

Instantly share code, notes, and snippets.

@pacozaa
Created September 19, 2024 08:22
Show Gist options
  • Save pacozaa/c7cb1850831a374d8ba6225e6687bbaa to your computer and use it in GitHub Desktop.
Save pacozaa/c7cb1850831a374d8ba6225e6687bbaa to your computer and use it in GitHub Desktop.
A python script to box the region image after run an ocr region from https://huggingface.co/spaces/Xenova/florence2-webgpu
import json
from PIL import Image, ImageDraw
# Load the input data from a JSON string
input_data = '''
{
"labels": [
"Active markets",
"Powered by Al | Data Retrived just now",
"C",
"North America",
"Europe, Middle East and Africa (EMEA)",
"2 COUNTRIES",
"8 COUNTRES",
"· United States",
"· United Kingdom",
"· Canada"
],
"quad_boxes": [
[
6.903,
42.745,
203.25500000000002,
42.745,
203.25500000000002,
65.985,
6.903,
65.985
],
[
942.643,
43.574999999999996,
1389.037,
43.574999999999996,
1389.037,
68.47500000000001,
942.643,
68.47500000000001
],
[
1464.203,
43.574999999999996,
1490.281,
43.574999999999996,
1490.281,
65.985,
1464.203,
65.985
],
[
94.341,
168.07500000000002,
312.169,
168.07500000000002,
312.169,
195.465,
94.341,
195.465
],
[
755.495,
166.41500000000002,
1316.939,
164.755,
1316.939,
198.785,
755.495,
200.445
],
[
94.341,
223.685,
240.071,
223.685,
240.071,
245.265,
94.341,
245.265
],
[
755.495,
223.685,
902.759,
223.685,
902.759,
245.265,
755.495,
245.265
],
[
111.21499999999999,
264.355,
307.567,
264.355,
307.567,
289.255,
111.21499999999999,
289.255
],
[
772.3689999999999,
264.355,
1004.0029999999999,
264.355,
1004.0029999999999,
291.745,
772.3689999999999,
290.91499999999996
],
[
111.21499999999999,
303.365,
241.605,
303.365,
241.605,
327.435,
111.21499999999999,
327.435
]
]
}
'''
# Parse the JSON data
data = json.loads(input_data)
# Load the image (replace 'your_image.jpg' with the path to your image)
image_path = '/Users/sarinsuriyakoon/Desktop/img3.png'
image = Image.open(image_path)
# Create a drawing context
draw = ImageDraw.Draw(image)
# Draw the quad boxes on the image
for box in data['quad_boxes']:
# Extract the coordinates
x1, y1, x2, y2, x3, y3, x4, y4 = box
# Draw the quadrilateral
draw.polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], outline="red")
# Save the image with the boxes drawn on it
output_image_path = 'image_with_boxes.png'
image.save(output_image_path)
print(f"Image with boxes saved to {output_image_path}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment