Search code examples
pythoncomputer-visiondetectron

In detectron2, how could I put the text on image?


I am learning how to use detectron2 well. And I could do predicting the bounding box. But, I also want to put the bounding box coordinate on the image. For this, I use cv2.putext library. but it did not work. Could you please make the below code can show bounding box coordinate on the images?

from detectron2.utils.visualizer import ColorMode
import glob
for imageName in glob.glob(os.path.join(test_path, '*jpg')):
  im = cv2.imread(imageName)
  outputs = predictor(im)
  v = Visualizer(im[:, :, ::-1],
            metadata=train_metadata,
            scale=0.8)
  out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
  cv2_imshow(out.get_image()[:, :, ::-1])

enter image description here


Solution

  • v = Visualizer(im[:, :, ::-1],
                metadata=train_metadata,
                scale=0.8)
    out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
    boxes = v._convert_boxes(outputs["instances"].pred_boxes.to('cpu')).squeeze()
    for box in boxes:
        out = v.draw_text(f"{box}", (box[0], box[1]))
    cv2_imshow(out.get_image()[:, :, ::-1])
    

    For draw_text function the first argument is text and the second argument is the position. For more check the following link.

    https://detectron2.readthedocs.io/modules/utils.html?highlight=draw_text#detectron2.utils.visualizer.Visualizer.draw_text