2/26/2023

Drawing rectangle and text on image using cv2, pillow (python code)

 Draw text & rectangle on image





Ver.1 pillow

.

from PIL import Image, ImageDraw, ImageFont
import json
# Display the image in Jupyter Notebook
from IPython.display import display


def draw_rect_text(base_dir, json_fn):
# Load JSON file
with open(base_dir+json_fn, 'r') as f:
data = json.load(f)

# Load image
img = Image.open(base_dir+data['image_file_name']+'.jpg')

# Create a draw object
draw = ImageDraw.Draw(img)

# Loop through OCR data and draw rectangles and text
for ocr in data['ocr']:
left = ocr['left']
top = ocr['top']
right = ocr['right']
bottom = ocr['bottom']
text = ocr['text']

# Draw rectangle
draw.rectangle((left, top, right, bottom), outline=(255, 0, 0), width=2)

# Draw text
font = ImageFont.truetype('arial.ttf', size=14)
text_size = draw.textsize(text, font=font)
text_x = left
text_y = top - text_size[1]
draw.text((text_x, text_y), text, font=font, fill=(255, 0, 0))

# Display image
# img.show() #now window
display(img) #display on notebook

..


Ver .2 cv2

.

import cv2
import json

def draw_rect_text(base_dir, json_fn):
# Load JSON file
with open(base_dir+json_fn, 'r') as f:
data = json.load(f)

print(base_dir+data['image_file_name']+'.jpg')
# Load image
img = cv2.imread(base_dir+data['image_file_name']+'.jpg')

# Loop through OCR data and draw rectangles and text
for ocr in data['ocr']:
left = ocr['left']
top = ocr['top']
right = ocr['right']
bottom = ocr['bottom']
text = ocr['text']
# Draw rectangle
cv2.rectangle(img, (left, top), (right, bottom), (0, 0, 255), 2)
# Draw text
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 1
text_size = cv2.getTextSize(text, font, font_scale, thickness)[0]
text_x = left
text_y = top - text_size[1]
cv2.putText(img, text, (text_x, text_y), font, font_scale, (0, 0, 255), thickness)
# Display image
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

..


Thank you.

πŸ™‡πŸ»‍♂️

www.marearts.com

No comments:

Post a Comment