brainai-spaces's picture
Update utils.py
324b868 verified
Raw
History Blame Contribute Delete
2.96 kB
import openvino as ov
import cv2
import numpy as np
core = ov.Core()
model = core.read_model(model='models/horizontal-text-detection-0001.xml')
compiled_model = core.compile_model(model = model, device_name="CPU")
input_layer = compiled_model.input(0)
output_layer = compiled_model.output(0)
def preprocess_data(image, input_layer):
N, C, H, W = input_layer.shape
resized_image = cv2.resize(image, (W, H))
input_image = np.expand_dims(resized_image.transpose(2, 0, 1), 0)
return input_image, resized_image
def predict_image(image, conf_threshold):
input_image, resized_image = preprocess_data(image, input_layer)
output_key = compiled_model.output("boxes")
boxes = compiled_model([input_image])[output_key]
#0์œผ๋กœ๋งŒ ๊ตฌ์„ฑ๋œ ์ƒ์ž ์ œ๊ฑฐ
boxes = boxes[~np.all(boxes == 0, axis=1)]
return boxes, resized_image
def convert_result_to_image(bgr_image, resized_image, boxes, threshold=0.3, conf_labels=True):
#๋ฐ”์šด๋”ฉ ๋ฐ•์Šค์™€ ๋ผ๋ฒจ์— ๋Œ€ํ•œ ์ƒ‰์ƒ ์ •์˜
colors = {"red": (255, 0, 0), "green": (0, 255, 0)}
#๋น„์œจ์„ ๊ณ„์‚ฐํ•˜๊ธฐ ์œ„ํ•ด ์ด๋ฏธ์ง€ shape ๊ฐ€์ ธ์˜ค๊ธฐ
(real_y, real_x), (resized_y, resized_x) = (
bgr_image.shape[:2],
resized_image.shape[:2],
)
ratio_x, ratio_y = real_x / resized_x, real_y / resized_y
#๊ธฐ๋ณธ ์ด๋ฏธ์ง€๋ฅผ BGR์—์„œ RGB ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜
rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
#0์ด ์•„๋‹Œ ์ƒ์ž ๋ฐ˜๋ณต
for box in boxes:
#๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ์œ„์น˜์—์„œ ์‹ ๋ขฐ๋„ ๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ
conf = box[-1]
if conf > threshold:
#float๋ฅผ int๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ๊ฐ ์ƒ์ž์˜ ๋ชจ์„œ๋ฆฌ ์œ„์น˜๋ฅผ x, y ๋น„์œจ๋กœ ๊ณฑํ•˜๊ธฐ
#์ด๋ฏธ์ง€ ์ƒ๋‹จ์— ๋ฐ”์šด๋”ฉ ๋ฐ•๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ
#์œ„์ชฝ ์ƒ์ž ๋ง‰๋Œ€๋ฅผ ์กฐ๊ธˆ ์•„๋ž˜๋กœ ์œ„์น˜์‹œ์ผœ ์ด๋ฏธ์ง€์—์„œ ๋ณด์ด๋„๋ก ์œ„์น˜ ์‹œํ‚ค๊ธฐ.
(x_min, y_min, x_max, y_max) = [
(int(max(corner_position * ratio_y, 10)) if idx % 2 else int(corner_position * ratio_x)) for idx, corner_position in enumerate(box[:-1])
]
#์œ„์น˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฐ”์šด๋”ฉ ๋ฐ•์Šค ๊ทธ๋ฆฌ๊ธฐ. ์‚ฌ๊ฐํ˜• ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ์ด๋ฏธ์ง€, ์‹œ์ž‘์ , ๋์ , ์ƒ‰์ƒ, ๋‘๊ป˜
rgb_image = cv2.rectangle(rgb_image, (x_min, y_min), (x_max, y_max), colors["green"], 3)
#์œ„์น˜์™€ ์‹ ๋ขฐ๋„์— ๋”ฐ๋ผ ์ด๋ฏธ์ง€์— ํ…์ŠคํŠธ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ธฐ
#ํ…์ŠคํŠธ ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜: ์ด๋ฏธ์ง€, ํ…์ŠคํŠธ, ์™ผ์ชฝ ํ•˜๋‹จ ๋ชจ์„œ๋ฆฌ ํ…์ŠคํŠธ ํ•„๋“œ, ๊ธ€๊ผด, ๊ธ€๊ผด ํฌ๊ธฐ, ์ƒ‰์ƒ, ๋‘๊ป˜, ์„  ์ข…๋ฅ˜.
if conf_labels:
rgb_image = cv2.putText(
rgb_image,
f"{conf:.2f}",
(x_min, y_min - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
colors["red"],
1,
cv2.LINE_AA,
)
return rgb_image