Python draw bounding boxes

60 Python code examples are found related to " draw bounding boxes". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: visualization.py    From CenterNet with MIT License 6 votes vote down vote up
def draw_bounding_boxes(image, gt_boxes, im_info):
  num_boxes = gt_boxes.shape[0]
  gt_boxes_new = gt_boxes.copy()
  gt_boxes_new[:,:4] = np.round(gt_boxes_new[:,:4].copy() / im_info[2])
  disp_image = Image.fromarray(np.uint8(image[0]))

  for i in range(num_boxes):
    this_class = int(gt_boxes_new[i, 4])
    disp_image = _draw_single_box(disp_image, 
                                gt_boxes_new[i, 0],
                                gt_boxes_new[i, 1],
                                gt_boxes_new[i, 2],
                                gt_boxes_new[i, 3],
                                'N%02d-C%02d' % (i, this_class),
                                FONT,
                                color=STANDARD_COLORS[this_class % NUM_COLORS])

  image[0, :] = np.array(disp_image)
  return image 
Example 2
Source File: visualization.py    From MSDS-RCNN with MIT License 6 votes vote down vote up
def draw_bounding_boxes(image, gt_boxes, im_info):
  num_boxes = gt_boxes.shape[0]
  gt_boxes_new = gt_boxes.copy()
  gt_boxes_new[:,:4] = np.round(gt_boxes_new[:,:4].copy() / im_info[2])
  disp_image = Image.fromarray(np.uint8(image[0]))

  for i in xrange(num_boxes):
    this_class = int(gt_boxes_new[i, 4])
    disp_image = _draw_single_box(disp_image, 
                                gt_boxes_new[i, 0],
                                gt_boxes_new[i, 1],
                                gt_boxes_new[i, 2],
                                gt_boxes_new[i, 3],
                                'N%02d-C%02d' % (i, this_class),
                                FONT,
                                color=STANDARD_COLORS[this_class % NUM_COLORS])

  image[0, :] = np.array(disp_image)
  return image 
Example 3
Source File: tensorflow_detection.py    From BMW-TensorFlow-Training-GUI with Apache License 2.0 6 votes vote down vote up
def draw_bounding_boxes(self, input_data, bboxes):
        """
        Draws bounding boxes on image and saves it.
        :param input_data: A single image
        :param bboxes: Bounding boxes
        :return:
        """
        left = 0
        top = 0
        conf = 0
        # image_path = '/main/result.jpg'
        image_path = '/main/' + str(input_data.filename)
        # open(image_path, 'wb').write(input_data.file.read())
        image = Image.open(image_path)
        draw = ImageDraw.Draw(image)
        for bbox in bboxes:
            draw.rectangle([bbox['coordinates']['left'], bbox['coordinates']['top'], bbox['coordinates']['right'],
                            bbox['coordinates']['bottom']], outline="red")
            left = bbox['coordinates']['left']
            top = bbox['coordinates']['top']
            conf = "{0:.2f}".format(bbox['confidence'])
            draw.text((int(left), int(top) - 20), str(conf) + "% " + str(bbox['ObjectClassName']), 'red', self.font)
        os.remove(image_path)
        image.save('/main/result.jpg', 'PNG') 
Example 4
Source File: label.py    From autowebcompat with Mozilla Public License 2.0 6 votes vote down vote up
def draw_bounding_boxes_init(param):
    [main_drawing_area, secondary_drawing_area, boxes] = param

    color = {'d': COLOR_D, 'n': COLOR_N}
    for boxes_type, boxes_values in all_boxes.items():
        for box in boxes_values:
            if box in boxes[boxes_type]:
                box_main_drawing_area = main_drawing_area
                box_secondary_drawing_area = secondary_drawing_area
            else:
                box_main_drawing_area = secondary_drawing_area
                box_secondary_drawing_area = main_drawing_area

            create_bounding_box(box_main_drawing_area, box[0], box[1], box[2], box[3], color[boxes_type])
            create_cross(box_main_drawing_area, box[0], box[1], box[2], box[3])
            create_plus(box_main_drawing_area, box[0], box[1], box[2], box[3])
            create_change_shape(box_main_drawing_area, box[0], box[1], box[2], box[3])
            create_toggle_nd(box_main_drawing_area, box[0], box[1], box[2], box[3])
            create_bounding_box(box_secondary_drawing_area, box[0], box[1], box[2], box[3], color[boxes_type]) 
Example 5
Source File: MeasureVisualizer.py    From OMR-Datasets with MIT License 6 votes vote down vote up
def draw_bounding_boxes_into_image(self, image_path: str, ground_truth_annotations_path: str):
        destination_path = image_path.replace(".png", "_annotated.png")
        image = Image.open(image_path)
        image = image.convert("RGB")

        with open(ground_truth_annotations_path, 'r') as gt_file:
            data = json.load(gt_file)

        blue = (0, 0, 255, 100)  # RGBA
        yellow = (255, 255, 0, 100)  # RGBA
        magenta = (255, 0, 255, 100)  # RGBA
        if self.draw_system_measures:
            self._draw_rectangles(data["system_measures"], image, blue)

        if self.draw_stave_measures:
            self._draw_rectangles(data["stave_measures"], image, magenta)

        if self.draw_staves:
            self._draw_rectangles(data["staves"], image, yellow)

        image.save(destination_path) 
Example 6
Source File: visualization.py    From SSH-TensorFlow with MIT License 6 votes vote down vote up
def draw_bounding_boxes(image, gt_boxes, im_info):
    num_boxes = gt_boxes.shape[0]
    gt_boxes_new = gt_boxes.copy()
    gt_boxes_new[:, :4] = np.round(gt_boxes_new[:, :4].copy() / im_info[2])
    disp_image = Image.fromarray(np.uint8(image[0]))

    for i in range(num_boxes):
        this_class = int(gt_boxes_new[i, 4])
        disp_image = _draw_single_box(disp_image,
                                      gt_boxes_new[i, 0],
                                      gt_boxes_new[i, 1],
                                      gt_boxes_new[i, 2],
                                      gt_boxes_new[i, 3],
                                      'N%02d-C%02d' % (i, this_class),
                                      FONT,
                                      color=STANDARD_COLORS[this_class % NUM_COLORS])

    image[0, :] = np.array(disp_image)
    return image 
Example 7
Source File: visualization_utils.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def draw_bounding_boxes_on_image_array(image,
                                       boxes,
                                       color='red',
                                       thickness=4,
                                       display_str_list_list=()):
  """Draws bounding boxes on image (numpy array).

  Args:
    image: a numpy array object.
    boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
           The coordinates are in normalized format between [0, 1].
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list_list: list of list of strings.
                           a list of strings for each bounding box.
                           The reason to pass a list of strings for a
                           bounding box is that it might contain
                           multiple labels.

  Raises:
    ValueError: if boxes is not a [N, 4] array
  """
  image_pil = Image.fromarray(image)
  draw_bounding_boxes_on_image(image_pil, boxes, color, thickness, display_str_list_list)
  np.copyto(image, np.array(image_pil)) 
Example 8
Source File: visualization_utils.py    From id-card-detector with MIT License 5 votes vote down vote up
def draw_bounding_boxes_on_image(image,
                                 boxes,
                                 color='red',
                                 thickness=4,
                                 display_str_list_list=()):
  """Draws bounding boxes on image.

  Args:
    image: a PIL.Image object.
    boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
           The coordinates are in normalized format between [0, 1].
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list_list: list of list of strings.
                           a list of strings for each bounding box.
                           The reason to pass a list of strings for a
                           bounding box is that it might contain
                           multiple labels.

  Raises:
    ValueError: if boxes is not a [N, 4] array
  """
  boxes_shape = boxes.shape
  if not boxes_shape:
    return
  if len(boxes_shape) != 2 or boxes_shape[1] != 4:
    raise ValueError('Input must be of size [N, 4]')
  for i in range(boxes_shape[0]):
    display_str_list = ()
    if display_str_list_list:
      display_str_list = display_str_list_list[i]
    draw_bounding_box_on_image(image, boxes[i, 0], boxes[i, 1], boxes[i, 2],
                               boxes[i, 3], color, thickness, display_str_list) 
Example 9
Source File: visualization_utils_color.py    From tensorflow-face-detection with Apache License 2.0 5 votes vote down vote up
def draw_bounding_boxes_on_image_array(image,
                                       boxes,
                                       color='red',
                                       thickness=4,
                                       display_str_list_list=()):
  """Draws bounding boxes on image (numpy array).

  Args:
    image: a numpy array object.
    boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
           The coordinates are in normalized format between [0, 1].
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list_list: list of list of strings.
                           a list of strings for each bounding box.
                           The reason to pass a list of strings for a
                           bounding box is that it might contain
                           multiple labels.

  Raises:
    ValueError: if boxes is not a [N, 4] array
  """
  image_pil = Image.fromarray(image)
  draw_bounding_boxes_on_image(image_pil, boxes, color, thickness,
                               display_str_list_list)
  np.copyto(image, np.array(image_pil)) 
Example 10
Source File: BoundingBoxes.py    From GAN_Review with MIT License 5 votes vote down vote up
def drawAllBoundingBoxes(self, image, imageName):
        bbxes = self.getBoundingBoxesByImageName(imageName)
        for bb in bbxes:
            if bb.getBBType() == BBType.GroundTruth:  # if ground truth
                image = add_bb_into_image(image, bb, color=(0, 255, 0))  # green
            else:  # if detection
                image = add_bb_into_image(image, bb, color=(255, 0, 0))  # red
        return image

    # def drawAllBoundingBoxes(self, image):
    #     for gt in self.getBoundingBoxesByType(BBType.GroundTruth):
    #         image = add_bb_into_image(image, gt ,color=(0,255,0))
    #     for det in self.getBoundingBoxesByType(BBType.Detected):
    #         image = add_bb_into_image(image, det ,color=(255,0,0))
    #     return image 
Example 11
Source File: utils.py    From nnabla with Apache License 2.0 5 votes vote down vote up
def draw_bounding_boxes(img, bboxes, names, colors=None, thresh=0.5):
    '''
    The transformed cordinates are further used to draw bounding boxes for the detected objects.

    Args:
        img (numpy.ndarray) : Input image
        bboxes (numpy.ndarray): 
            Transformed bounding box coorinates from the model.
        names (list of str): Name of categories in the dataset
        colors (list of tuple of 3 ints): Colors for bunding boxes
        thresh (float): Threshold of bounding boxes.

    '''
    if colors is None:
        rng = np.random.RandomState(1223)
        colors = rng.randint(0, 256, (len(names), 3)).astype(np.uint8)
        colors = [tuple(c.tolist()) for c in colors]

    im_h, im_w = img.shape[:2]
    draw = DrawBoundingBoxes(img, colors)
    for bb in bboxes:
        x, y, w, h = bb[:4]
        dw = w / 2.
        dh = h / 2.
        x0 = int(np.clip(x - dw, 0, im_w))
        y0 = int(np.clip(y - dh, 0, im_h))
        x1 = int(np.clip(x + dw, 0, im_w))
        y1 = int(np.clip(y + dh, 0, im_h))
        det_ind = np.where(bb[5:] > thresh)[0]
        if len(det_ind) == 0:
            continue
        prob = bb[5 + det_ind]
        label = ', '.join("{}: {:.2f}%".format(
            names[det_ind[j]], prob[j] * 100) for j in range(len(det_ind)))
        print("[INFO] {}".format(label))
        draw.draw((x0, y0, x1, y1), det_ind[0], label)
    return draw.get() 
Example 12
Source File: gen_image_ops.py    From keras-lambda with MIT License 5 votes vote down vote up
def draw_bounding_boxes(images, boxes, name=None):
  r"""Draw bounding boxes on a batch of images.

  Outputs a copy of `images` but draws on top of the pixels zero or more bounding
  boxes specified by the locations in `boxes`. The coordinates of the each
  bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The
  bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and
  height of the underlying image.

  For example, if an image is 100 x 200 pixels and the bounding box is
  `[0.1, 0.2, 0.5, 0.9]`, the bottom-left and upper-right coordinates of the
  bounding box will be `(10, 40)` to `(50, 180)`.

  Parts of the bounding box may fall outside the image.

  Args:
    images: A `Tensor`. Must be one of the following types: `float32`, `half`.
      4-D with shape `[batch, height, width, depth]`. A batch of images.
    boxes: A `Tensor` of type `float32`.
      3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding
      boxes.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `images`.
    4-D with the same shape as `images`. The batch of input images with
    bounding boxes drawn on the images.
  """
  result = _op_def_lib.apply_op("DrawBoundingBoxes", images=images,
                                boxes=boxes, name=name)
  return result 
Example 13
Source File: visualization.py    From iCAN with MIT License 5 votes vote down vote up
def draw_bounding_boxes_HOI(image, gt_boxes, gt_class):
  num_boxes = gt_boxes.shape[0]
  gt_boxes_new = gt_boxes.copy()
  gt_boxes_new = np.round(gt_boxes_new[:,1:].copy())
  disp_image = Image.fromarray(np.uint8(image[0]))


  show_list = [99,99,99,99,99,99,99,99]
  count = 0
  for idx, val in enumerate(gt_class[0,:]):
    if val != 0:
      show_list[count] = idx
      count += 1


  #for i in range(1): # change num_boxes to 2
  for i in [2]: #  show the third boxes
    this_class = 0
    disp_image = _draw_single_box(disp_image, 
                                gt_boxes_new[i, 0],
                                gt_boxes_new[i, 1],
                                gt_boxes_new[i, 2],
                                gt_boxes_new[i, 3],
                                '%01d-%01d-%01d-%01d-%01d-%01d-%01d-%01d' % (show_list[0], show_list[1], show_list[2], show_list[3], show_list[4], show_list[5], show_list[6], show_list[7]),
                                FONT,
                                color='Red')

  image[0, :] = np.array(disp_image)
  return image 
Example 14
Source File: visualization_utils.py    From mtl-ssl with Apache License 2.0 5 votes vote down vote up
def draw_bounding_boxes_on_image(image,
                                 boxes,
                                 color='red',
                                 thickness=2,
                                 display_str_list_list=(),
                                 font_size=24):
  """Draws bounding boxes on image.

  Args:
    image: a PIL.Image object.
    boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
           The coordinates are in normalized format between [0, 1].
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list_list: list of list of strings.
                           a list of strings for each bounding box.
                           The reason to pass a list of strings for a
                           bounding box is that it might contain
                           multiple labels.

  Raises:
    ValueError: if boxes is not a [N, 4] array
  """
  boxes_shape = boxes.shape
  if not boxes_shape:
    return
  if len(boxes_shape) != 2 or boxes_shape[1] != 4:
    raise ValueError('Input must be of size [N, 4]')
  for i in range(boxes_shape[0]):
    display_str_list = ()
    if display_str_list_list:
      display_str_list = display_str_list_list[i]
    draw_bounding_box_on_image(image, boxes[i, 0], boxes[i, 1], boxes[i, 2],
                               boxes[i, 3], color, thickness, display_str_list,
                               font_size=font_size) 
Example 15
Source File: visualization.py    From iCAN with MIT License 5 votes vote down vote up
def draw_bounding_boxes_HOI_PIC(image, gt_boxes, gt_class):
  num_boxes = gt_boxes.shape[0]
  gt_boxes_new = gt_boxes.copy()
  gt_boxes_new = np.round(gt_boxes_new[:,1:].copy())
  disp_image = Image.fromarray(np.uint8(image[0]))


  show_list = [99,99,99,99,99,99,99,99]
  count = 0
  for idx, val in enumerate(gt_class[0,:]):
    if val != 0:
      show_list[count] = idx
      count += 1
  show_list[1] = gt_boxes_new[2, 0]
  show_list[2] = gt_boxes_new[2, 1]
  show_list[3] = gt_boxes_new[2, 2]
  show_list[4] = gt_boxes_new[2, 3]


  #for i in range(1): # change num_boxes to 2
  for i in [2]: #  show the third boxes
    this_class = 0
    disp_image = _draw_single_box(disp_image, 
                                gt_boxes_new[i, 0],
                                gt_boxes_new[i, 1],
                                gt_boxes_new[i, 2],
                                gt_boxes_new[i, 3],
                                '%01d-%01d-%01d-%01d-%01d-%01d-%01d-%01d' % (show_list[0], show_list[1], show_list[2], show_list[3], show_list[4], show_list[5], show_list[6], show_list[7]),
                                FONT,
                                color='Red')

  image[0, :] = np.array(disp_image)
  return image 
Example 16
Source File: darkflow_engine.py    From BerryNet with GNU General Public License v3.0 5 votes vote down vote up
def drawBoundingBoxes(imageData, imageOutputPath, inferenceResults, colorMap):
    """Draw bounding boxes on an image.

    imageData: image data in numpy array format
    imageOutputPath: output image file path
    inferenceResults: Darkflow inference results
    colorMap: Bounding box color candidates, list of RGB tuples.
    """
    # TODO: return raw data instead of save image
    for res in inferenceResults:
        left = res['topleft']['x']
        top = res['topleft']['y']
        right = res['bottomright']['x']
        bottom = res['bottomright']['y']
        colorIndex = res['coloridx']
        color = colorMap[colorIndex]
        label = res['label']
        confidence = res['confidence']
        imgHeight, imgWidth, _ = imageData.shape
        thick = int((imgHeight + imgWidth) // 300)

        cv2.rectangle(imageData,(left, top), (right, bottom), color, thick)
        cv2.putText(imageData, label, (left, top - 12), 0, 1e-3 * imgHeight,
            color, thick//3)
    cv2.imwrite(imageOutputPath, imageData)
    logging.debug('Save bounding box result image to {}'.format(imageOutputPath)) 
Example 17
Source File: yolov2_detection.py    From nnabla-examples with Apache License 2.0 5 votes vote down vote up
def draw_bounding_boxes(img, bboxes, im_w, im_h, names, colors, sub_w, sub_h, thresh):
    draw = DrawBoundingBoxes(img, colors)
    for bb in bboxes:
        if bb[4] <= 0:
            continue
        # x, y, w, h = bb[:4] * np.array([im_w, im_h, im_w, im_h])
        x, y, w, h = bb[:4]
        x = (x - (1 - sub_w) / 2.) / sub_w * im_w
        y = (y - (1 - sub_h) / 2.) / sub_h * im_h
        w = w * im_w / sub_w
        h = h * im_h / sub_h
        dw = w / 2.
        dh = h / 2.
        x0 = int(np.clip(x - dw, 0, im_w))
        y0 = int(np.clip(y - dh, 0, im_h))
        x1 = int(np.clip(x + dw, 0, im_w))
        y1 = int(np.clip(y + dh, 0, im_h))
        det_ind = np.where(bb[5:] > thresh)[0]
        if len(det_ind) == 0:
            continue
        prob = bb[5 + det_ind]
        # Object detection with deep learning and OpenCV
        # https://goo.gl/q4RdcZ
        label = ', '.join("{}: {:.2f}%".format(
            names[det_ind[j]], prob[j] * 100) for j in range(len(det_ind)))
        print("[INFO] {}".format(label))
        draw.draw((x0, y0, x1, y1), det_ind[0], label)
    return draw.get() 
Example 18
Source File: visualization_utils.py    From Counting-people-video with MIT License 5 votes vote down vote up
def draw_bounding_boxes_on_image_array(image,
                                       boxes,
                                       color='red',
                                       thickness=4,
                                       display_str_list_list=()):
    """Draws bounding boxes on image (numpy array).

    Args:
      image: a numpy array object.
      boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
             The coordinates are in normalized format between [0, 1].
      color: color to draw bounding box. Default is red.
      thickness: line thickness. Default value is 4.
      display_str_list_list: list of list of strings.
                             a list of strings for each bounding box.
                             The reason to pass a list of strings for a
                             bounding box is that it might contain
                             multiple labels.

    Raises:
      ValueError: if boxes is not a [N, 4] array
    """
    image_pil = Image.fromarray(image)
    draw_bounding_boxes_on_image(image_pil, boxes, color, thickness,
                                 display_str_list_list)
    np.copyto(image, np.array(image_pil)) 
Example 19
Source File: visualization_utils.py    From Counting-people-video with MIT License 5 votes vote down vote up
def draw_bounding_boxes_on_image(image,
                                 boxes,
                                 color='red',
                                 thickness=4,
                                 display_str_list_list=()):
    """Draws bounding boxes on image.

    Args:
      image: a PIL.Image object.
      boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).
             The coordinates are in normalized format between [0, 1].
      color: color to draw bounding box. Default is red.
      thickness: line thickness. Default value is 4.
      display_str_list_list: list of list of strings.
                             a list of strings for each bounding box.
                             The reason to pass a list of strings for a
                             bounding box is that it might contain
                             multiple labels.

    Raises:
      ValueError: if boxes is not a [N, 4] array
    """
    boxes_shape = boxes.shape
    if not boxes_shape:
        return
    if len(boxes_shape) != 2 or boxes_shape[1] != 4:
        raise ValueError('Input must be of size [N, 4]')
    for i in range(boxes_shape[0]):
        display_str_list = ()
        if display_str_list_list:
            display_str_list = display_str_list_list[i]
        draw_bounding_box_on_image(image, boxes[i, 0], boxes[i, 1], boxes[i, 2],
                                   boxes[i, 3], color, thickness, display_str_list) 
Example 20
Source File: visualization.py    From kaggle-imaterialist with MIT License 5 votes vote down vote up
def draw_bounding_boxes_on_image_array(
    image, bboxes, color=INDIGO, thickness=4, use_normalized_coordinates=True, fontsize=20
):
    image_pil = Image.fromarray(image)
    draw_bounding_boxes_on_image(image_pil, bboxes, color, thickness, use_normalized_coordinates, fontsize)
    np.copyto(image, np.array(image_pil))