import json import glob from pathlib import Path import cv2 import numpy as np def draw_box(pth_webp, pth_boxs): with open(pth_boxs, encoding='utf-8') as fp: boxs = json.load(fp) word_boxes = boxs['text_word_boxes'] word_boxes = word_boxes[::-1] # 逆序 text_word = boxs['text_word'] text_word = text_word[::-1] rec_texts = boxs['rec_texts'] rec_texts = rec_texts[::-1] fp.close() imgData = np.fromfile(pth_webp, dtype=np.uint8) img = cv2.imdecode(imgData, cv2.IMREAD_UNCHANGED) if len(img.shape) != 3: # 转彩图 img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # DBNet 原版只能处理彩图,这里转一下 else: img_color = img.copy() for arr_word, arr_box in zip( text_word, word_boxes): for word, box in zip(arr_word, arr_box): lu = [box[0], box[1]] rd = [box[2], box[3]] ld = [box[0], box[3]] ru = [box[2], box[1]] points = np.array([lu, ru, rd, ld]) cv2.polylines(img_color, [points], isClosed=True, color=( # 多边形,框得比较全 100, 0, 255), thickness=2) # 只画线,不填充 cv2.imshow("box", img_color) cv2.waitKey(0) path_jpg = pth_webp.replace(".png", ".jpg") cv2.imwrite(path_jpg, img_color) def do_drawbox(): pth_box = 'output/SWX0005_00000_00001_res.json' pth_webp = 'output/SWX0005_00000_00001_input_img.png' draw_box(pth_webp, pth_box) if __name__ == "__main__": do_drawbox()