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