Python matplotlib.pyplot.Rectangle() Examples

The following are code examples for showing how to use matplotlib.pyplot.Rectangle(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Deformable-ConvNets   Author: guanfuchen   File: show_boxes.py    MIT License 6 votes vote down vote up
def show_boxes(im, dets, classes, scale = 1.0):
    plt.cla()
    plt.axis("off")
    plt.imshow(im)
    for cls_idx, cls_name in enumerate(classes):
        cls_dets = dets[cls_idx]
        for det in cls_dets:
            bbox = det[:4] * scale
            color = (rand(), rand(), rand())
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                  bbox[2] - bbox[0],
                                  bbox[3] - bbox[1], fill=False,
                                  edgecolor=color, linewidth=2.5)
            plt.gca().add_patch(rect)

            if cls_dets.shape[1] == 5:
                score = det[-1]
                plt.gca().text(bbox[0], bbox[1],
                               '{:s} {:.3f}'.format(cls_name, score),
                               bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white')
    plt.show()
    return im 
Example 2
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 6 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis() 
Example 3
Project: pytorch-lstd   Author: JiasiWang   File: eval.py    MIT License 6 votes vote down vote up
def vis(im, index, dets, w, h, thresh=0.0):
    import numpy as np
    import matplotlib.pyplot as plt
    npimg = im.cpu().numpy()
    npimg = (npimg + 128)/255
    im = np.transpose(npimg, (1, 2, 0))
    plt.cla()
    plt.imshow(im)
    #print(bbox) 
    for i in range(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.gca().add_patch(
                plt.Rectangle((bbox[0]*300/w, bbox[1]*300/h),
                              (bbox[2] - bbox[0])*300/w,
                              (bbox[3] - bbox[1])*300/h, fill=False,
                              edgecolor='g', linewidth=3)
                )
    plt.show() 
Example 4
Project: Deep-Feature-Flow-Segmentation   Author: tonysy   File: show_boxes.py    MIT License 6 votes vote down vote up
def show_boxes(im, dets, classes, scale = 1.0):
    plt.cla()
    plt.axis("off")
    plt.imshow(im)
    for cls_idx, cls_name in enumerate(classes):
        cls_dets = dets[cls_idx]
        for det in cls_dets:
            bbox = det[:4] * scale
            color = (rand(), rand(), rand())
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                  bbox[2] - bbox[0],
                                  bbox[3] - bbox[1], fill=False,
                                  edgecolor=color, linewidth=2.5)
            plt.gca().add_patch(rect)

            if cls_dets.shape[1] == 5:
                score = det[-1]
                plt.gca().text(bbox[0], bbox[1],
                               '{:s} {:.3f}'.format(cls_name, score),
                               bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white')
    plt.show()
    return im 
Example 5
Project: TFFRCNN   Author: CharlesShang   File: minibatch.py    MIT License 6 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 6
Project: TFFRCNN   Author: CharlesShang   File: test.py    MIT License 6 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.8):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt 
    #im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4] 
        score = dets[i, -1] 
        if score > thresh:
            #plt.cla()
            #plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.gca().text(bbox[0], bbox[1] - 2,
                 '{:s} {:.3f}'.format(class_name, score),
                 bbox=dict(facecolor='blue', alpha=0.5),
                 fontsize=14, color='white')

            plt.title('{}  {:.3f}'.format(class_name, score))
    #plt.show() 
Example 7
Project: pytorch-detect-rfcn   Author: Feynman27   File: roibatchLoader.py    MIT License 6 votes vote down vote up
def _plot_image(self, data, gt_boxes, num_boxes):
      import matplotlib.pyplot as plt
      X=data.cpu().numpy().copy()
      X += cfg.PIXEL_MEANS
      X = X.astype(np.uint8) 
      X = X.squeeze(0)
      boxes = gt_boxes[:num_boxes,:].cpu().numpy().copy()

      fig, ax = plt.subplots(figsize=(8,8))
      ax.imshow(X[:,:,::-1], aspect='equal')
      for i in range(boxes.shape[0]):
          bbox = boxes[i, :4]
          ax.add_patch(
                  plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2]-bbox[0],
                                 bbox[3]-bbox[1], fill=False, linewidth=2.0)
                  )
      #plt.imshow(X[:,:,::-1])
      plt.tight_layout()
      plt.show() 
Example 8
Project: Detection_and_Recognition_in_Remote_Sensing_Image   Author: whywhs   File: show_boxes.py    Apache License 2.0 6 votes vote down vote up
def show_boxes(im, dets, classes, scale = 1.0):
    plt.cla()
    plt.axis("off")
    plt.imshow(im)
    for cls_idx, cls_name in enumerate(classes):
        cls_dets = dets[cls_idx]
        for det in cls_dets:
            bbox = det[:4] * scale
            color = (rand(), rand(), rand())
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                  bbox[2] - bbox[0],
                                  bbox[3] - bbox[1], fill=False,
                                  edgecolor=color, linewidth=2.5)
            plt.gca().add_patch(rect)

            if cls_dets.shape[1] == 5:
                score = det[-1]
                plt.gca().text(bbox[0], bbox[1],
                               '{:s} {:.3f}'.format(cls_name, score),
                               bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white')
    plt.show()
    return im 
Example 9
Project: RetinaNet   Author: xmyqsh   File: minibatch.py    MIT License 6 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 10
Project: RetinaNet   Author: xmyqsh   File: test.py    MIT License 6 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.8):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt 
    #im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4] 
        score = dets[i, -1] 
        if score > thresh:
            #plt.cla()
            #plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.gca().text(bbox[0], bbox[1] - 2,
                 '{:s} {:.3f}'.format(class_name, score),
                 bbox=dict(facecolor='blue', alpha=0.5),
                 fontsize=14, color='white')

            plt.title('{}  {:.3f}'.format(class_name, score))
    #plt.show() 
Example 11
Project: RetinaNet   Author: xmyqsh   File: minibatch.py    MIT License 6 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, sublabels_blob):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[2:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        subcls = sublabels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' subclass: ', subcls
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 12
Project: pytorch-detect-to-track   Author: Feynman27   File: roibatchLoader.py    MIT License 6 votes vote down vote up
def _plot_image(self, data, gt_boxes, num_boxes):
      import matplotlib.pyplot as plt
      X=data.cpu().numpy().copy()
      X += cfg.PIXEL_MEANS
      X = X.astype(np.uint8) 
      X = X.squeeze(0)
      boxes = gt_boxes.squeeze(0)[:num_boxes.view(-1)[0],:].cpu().numpy().copy()

      fig, ax = plt.subplots(figsize=(8,8))
      ax.imshow(X[:,:,::-1], aspect='equal')
      for i in range(boxes.shape[0]):
          bbox = boxes[i, :4]
          ax.add_patch(
                  plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2]-bbox[0],
                                 bbox[3]-bbox[1], fill=False, linewidth=2.0)
                  )
      #plt.imshow(X[:,:,::-1])
      plt.tight_layout()
      plt.show() 
Example 13
Project: RPN   Author: hfut721   File: minibatch.py    MIT License 6 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 14
Project: RPN   Author: hfut721   File: test.py    MIT License 6 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show() 
Example 15
Project: OCR   Author: DongfeiJi   File: minibatch.py    Apache License 2.0 6 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in range(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print('class: ', cls, ' overlap: ', overlaps[i])
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 16
Project: dpl   Author: ppengtang   File: test.py    MIT License 6 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.3):
    """Visual debugging of detections."""
    import matplotlib.pyplot as plt
    im = im[:, :, (2, 1, 0)]
    for i in xrange(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.cla()
            plt.imshow(im)
            plt.gca().add_patch(
                plt.Rectangle((bbox[0], bbox[1]),
                              bbox[2] - bbox[0],
                              bbox[3] - bbox[1], fill=False,
                              edgecolor='g', linewidth=3)
                )
            plt.title('{}  {:.3f}'.format(class_name, score))
            plt.show() 
Example 17
Project: pytorch_RFCN   Author: xingmimfl   File: minibatch.py    MIT License 6 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    for i in xrange(rois_blob.shape[0]):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' overlap: ', overlaps[i]
        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 18
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 19
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
        )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 20
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: vis.py    Apache License 2.0 5 votes vote down vote up
def vis_detection(im_orig, detections, class_names, thresh=0.7):
    """visualize [cls, conf, x1, y1, x2, y2]"""
    import matplotlib.pyplot as plt
    import random
    plt.imshow(im_orig)
    colors = [(random.random(), random.random(), random.random()) for _ in class_names]
    for [cls, conf, x1, y1, x2, y2] in detections:
        cls = int(cls)
        if cls > 0 and conf > thresh:
            rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
                                 fill=False, edgecolor=colors[cls], linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(x1, y1 - 2, '{:s} {:.3f}'.format(class_names[cls], conf),
                           bbox=dict(facecolor=colors[cls], alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 21
Project: Deformable-ConvNets   Author: guanfuchen   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            if score < threshold:
                continue
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 22
Project: Deformable-ConvNets   Author: guanfuchen   File: show_offset.py    MIT License 5 votes vote down vote up
def show_boxes_simple(bbox, color='r', lw=2):
    rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=lw)
    plt.gca().add_patch(rect) 
Example 23
Project: Deformable-ConvNets   Author: guanfuchen   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            if score < threshold:
                continue
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 24
Project: Deformable-ConvNets   Author: guanfuchen   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            if score < threshold:
                continue
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 25
Project: insightface   Author: deepinsight   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, config.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 26
Project: pyplis   Author: jgliss   File: fluxcalc.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_bg_roi_rect(self, ax=None, to_pyrlevel=0):
        """Plot rectangular area used for background check."""
        roi = map_roi(self.settings.bg_roi_abs, to_pyrlevel)
        x, y, w, h = roi2rect(roi)
        r = Rectangle(xy=(x, y), width=w, height=h, fc="none", ec="r")
        ax.add_artist(r)
        return ax 
Example 27
Project: Deep-Feature-Flow-Segmentation   Author: tonysy   File: show_offset.py    MIT License 5 votes vote down vote up
def show_boxes_simple(bbox, color='r', lw=2):
    rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=lw)
    plt.gca().add_patch(rect) 
Example 28
Project: chainer-sort   Author: knorth55   File: vis_tracking_bbox.py    MIT License 5 votes vote down vote up
def vis_tracking_bbox(
        img, bbox, inst_id, label=None, score=None,
        label_names=None, alpha=1.0, ax=None):

    from matplotlib import pyplot as plot
    ax = vis_image(img, ax=ax)

    assert len(bbox) == len(inst_id)
    if len(bbox) == 0:
        return ax

    for i, (bb, inst_i) in enumerate(zip(bbox, inst_id)):
        bb = np.round(bb).astype(np.int32)
        y_min, x_min, y_max, x_max = bb
        color = np.array(_default_cmap(inst_i + 1)) / 255.

        ax.add_patch(plot.Rectangle(
            (x_min, y_min), x_max - x_min, y_max - y_min,
            fill=False, edgecolor=color, linewidth=3))

        caption = []
        caption.append('{}'.format(inst_i))

        if label is not None and label_names is not None:
            lb = label[i]
            if not (0 <= lb < len(label_names)):
                raise ValueError('No corresponding name is given')
            caption.append(label_names[lb])
        if score is not None:
            sc = score[i]
            caption.append('{:.2f}'.format(sc))

        ax.text((x_max + x_min) / 2, y_min,
                ': '.join(caption),
                style='italic',
                bbox={'facecolor': color, 'alpha': alpha},
                fontsize=8, color='white') 
Example 29
Project: TFFRCNN   Author: CharlesShang   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, ax, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
        )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 30
Project: TFFRCNN   Author: CharlesShang   File: minibatch2.py    MIT License 5 votes vote down vote up
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps, sublabels_blob, view_targets_blob=None, view_inside_blob=None):
    """Visualize a mini-batch for debugging."""
    import matplotlib.pyplot as plt
    import math
    for i in xrange(min(rois_blob.shape[0], 10)):
        rois = rois_blob[i, :]
        im_ind = rois[0]
        roi = rois[1:]
        im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
        im += cfg.PIXEL_MEANS
        im = im[:, :, (2, 1, 0)]
        im = im.astype(np.uint8)
        cls = labels_blob[i]
        subcls = sublabels_blob[i]
        plt.imshow(im)
        print 'class: ', cls, ' subclass: ', subcls, ' overlap: ', overlaps[i]

        start = 3 * cls
        end = start + 3
        # print 'view: ', view_targets_blob[i, start:end] * 180 / math.pi
        # print 'view weights: ', view_inside_blob[i, start:end]

        plt.gca().add_patch(
            plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
                          roi[3] - roi[1], fill=False,
                          edgecolor='r', linewidth=3)
            )
        plt.show() 
Example 31
Project: TFFRCNN   Author: CharlesShang   File: generate.py    MIT License 5 votes vote down vote up
def _vis_proposals(im, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    class_name = 'obj'
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 32
Project: SiamFC-TensorFlow   Author: mingfx   File: show_tracking.py    MIT License 5 votes vote down vote up
def create_bbox(bbox, color):
  return Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3],
                   fill=False,  # remove background\n",
                   edgecolor=color) 
Example 33
Project: lambda-deep-learning-demo   Author: lambdal   File: object_detection_client.py    Apache License 2.0 5 votes vote down vote up
def display_ori(image, outputs_dict):
  s = outputs_dict["output_scores"]
  l = outputs_dict["output_labels"]
  b = outputs_dict["output_bboxes"]

  h, w = image.shape[:2]
    
  plt.imshow(image)
  currentAxis = plt.gca()

  for score, label, box in zip(s, l, b):
    if score > THRESHOLD:
      box = np.asarray(box) * np.asarray([float(w), float(h), float(w), float(h)])
      xmin = np.clip(box[0], 0, w)
      ymin = np.clip(box[1], 0, h)
      xmax = np.clip(box[2], 0, w)
      ymax = np.clip(box[3], 0, h)
      label_name = MSCOCO_CAT_NAME[label - 1]

      display_txt = '%s: %.2f'%(label_name, score)

      coords = (xmin, ymin), xmax-xmin+1, ymax-ymin+1
      color = COLORS[label]

      currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))
      currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5})

  plt.axis('off')
  plt.show() 
Example 34
Project: lambda-deep-learning-demo   Author: lambdal   File: infer_display_object_detection.py    Apache License 2.0 5 votes vote down vote up
def display_ori(self, outputs_dict):
    for s, l, b, a, scale, translation, file_name in zip(
      outputs_dict["scores"],
      outputs_dict["labels"],
      outputs_dict["bboxes"],
      outputs_dict["anchors"],
      outputs_dict["scales"],
      outputs_dict["translations"],
      outputs_dict["file_name"]):

      input_image = misc.imread(file_name).astype(np.float32) / 255.0
      h, w = input_image.shape[:2]

      
      plt.imshow(input_image)
      currentAxis = plt.gca()

      for score, label, box in zip(s, l, b):
        box = box * [float(w), float(h), float(w), float(h)]
        xmin = np.clip(box[0], 0, w)
        ymin = np.clip(box[1], 0, h)
        xmax = np.clip(box[2], 0, w)
        ymax = np.clip(box[3], 0, h)
        label_name = MSCOCO_CAT_NAME[label - 1]

        display_txt = '%s: %.2f'%(label_name, score)

        coords = (xmin, ymin), xmax-xmin+1, ymax-ymin+1
        color = COLORS[label]

        currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))
        currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5})

      plt.axis('off')
      plt.show() 
Example 35
Project: pytorch-FPN   Author: yxgeee   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 36
Project: tf-faster-rcnn-relation-module   Author: ChengpengChen   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 37
Project: tf-faster-rcnn-relation-module   Author: ChengpengChen   File: demo_vis.py    MIT License 5 votes vote down vote up
def vis_detections_col(im, class_name, dets, col_ind=0, thresh=0.5):
  """Draw detected bounding boxes."""
  inds = np.where(dets[:, -1] >= thresh)[0]
  if len(inds) == 0:
    return

  im = im[:, :, (2, 1, 0)]
  fig, ax = plt.subplots(figsize=(12, 12))
  ax.imshow(im, aspect='equal')
  for i in inds:
    bbox = dets[i, :4]
    score = dets[i, -1]

    ax.add_patch(
      plt.Rectangle((bbox[0], bbox[1]),
                    bbox[2] - bbox[0],
                    bbox[3] - bbox[1], fill=False,
                    edgecolor=STANDARD_COLORS[col_ind], linewidth=3.5)
    )
    ax.text(bbox[0], bbox[1] - 2,
            '{:s} {:.3f}'.format(class_name, score),
            bbox=dict(facecolor='blue', alpha=0.5),
            fontsize=14, color='white')

  ax.set_title(('{} detections with '
                'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                thresh),
               fontsize=14)
  plt.axis('off')
  plt.tight_layout()
  plt.draw() 
Example 38
Project: tf-faster-rcnn-relation-module   Author: ChengpengChen   File: demo_vis.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 39
Project: tf-faster-rcnn-relation-module   Author: ChengpengChen   File: demo_vis.py    MIT License 5 votes vote down vote up
def vis_detections_one_img(im, im_name, boxes, scores, NMS_THRESH=0.3, thresh=0.5):
  im = im[:, :, (2, 1, 0)]
  fig, ax = plt.subplots(figsize=(12, 12))
  ax.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='off')
  ax.imshow(im, aspect='equal')

  for cls_ind, cls in enumerate(CLASSES[1:]):
    cls_ind += 1  # because we skipped background
    cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]
    cls_scores = scores[:, cls_ind]
    dets = np.hstack((cls_boxes,
                      cls_scores[:, np.newaxis])).astype(np.float32)
    keep = nms(dets, NMS_THRESH)
    dets = dets[keep, :]

    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
      continue

    for i in inds:
      bbox = dets[i, :4]
      score = dets[i, -1]

      ax.add_patch(
        plt.Rectangle((bbox[0], bbox[1]),
                      bbox[2] - bbox[0],
                      bbox[3] - bbox[1], fill=False,
                      edgecolor=STANDARD_COLORS[cls_ind], linewidth=3.5)
      )
      ax.text(bbox[0], bbox[1] - 2,
              '{:s} {:.3f}'.format(cls, score),
              bbox=dict(facecolor='blue', alpha=0.5),
              fontsize=14, color='white')
  fig.savefig(os.path.join('demo_save', im_name), format='jpg')

  plt.axis('off')
  plt.tight_layout()
  plt.draw() 
Example 40
Project: BaRC   Author: StanfordASL   File: planarQuad.py    MIT License 5 votes vote down vote up
def plot_quad_in_map(self):
        x = self.state[0]
        y = self.state[2]
        th = self.state[4]
        r_quad = self.quad_rad
        
        ray_angles = self.get_ray_angles()
        ray_measurements = [self.ray_dist(x,y,th_r) for th_r in ray_angles]

        x_points = x + ray_measurements*np.cos(ray_angles)
        y_points = y + ray_measurements*np.sin(ray_angles)

        for xi, yi in zip(x_points, y_points):
            plt.plot([x,xi], [y, yi], color='r', linestyle=':', alpha=0.5)
        plt.plot(x_points, y_points, marker='+', color='r', linestyle='none')
        ax = plt.gca()
        for xo,yo,ro in zip(self.obst_X, self.obst_Y, self.obst_R):
            c = plt.Circle((xo,yo),ro, color='black', alpha=1.0)
            ax.add_artist(c)
       
        r = plt.Rectangle((self.xg_lower, self.yg_lower), self.xg_upper-self.xg_lower, self.yg_upper - self.yg_lower, color='g', alpha=0.3, hatch='/')
        ax.add_artist(r)

        plt.plot([x - r_quad*np.cos(th), x + r_quad*np.cos(th)], [y - r_quad*np.sin(th), y + r_quad*np.sin(th)], marker='o', linewidth=2, color='b', markersize=5)

        plt.xlim([self.x_lower, self.x_upper])
        plt.ylim([self.y_lower, self.y_upper]) 
Example 41
Project: SiamFC-TensorFlow   Author: bilylee   File: show_tracking.py    MIT License 5 votes vote down vote up
def create_bbox(bbox, color):
  return Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3],
                   fill=False,  # remove background\n",
                   edgecolor=color) 
Example 42
Project: SSH-TensorFlow   Author: wanjinchang   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='green', linewidth=2)
            )
        # ax.text(bbox[0], bbox[1] - 2,
        #         '{:s} {:.3f}'.format(class_name, score),
        #         bbox=dict(facecolor='blue', alpha=0.5),
        #         fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 43
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def set_axis_settings_for_contour_plots(self, ax):
        if self.boxtype == 'circular':
            circle1=plt.Circle((0,0), self.radius, ec='black', fc='none', lw=2)
            ax.add_artist(circle1)
        if self.boxtype == 'linear':
            rectangle1=plt.Rectangle((-self.radius, -self.radius),
                    2*self.radius, 2*self.radius, ec='black', fc='none', lw=2)
            ax.add_artist(rectangle1)
        ax.set_aspect('equal')
        ax.set_xticks([])
        ax.set_yticks([]) 
Example 44
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def _uniform_noise_rectangle(self):
		"""
		Plots a rectangle that indicate the uniform noise
		"""
		central_center = np.array([0, 0])
		xy = (central_center[0] - self.spacing[0] / 2.,
			  central_center[1] - self.spacing[1] / 2.)
		rectangle1=plt.Rectangle(xy, self.spacing[0], self.spacing[1],
								 ec=color_cycle_blue3[0], fc=color_cycle_blue3[0], lw=2)
		plt.gca().add_artist(rectangle1)
		plt.text(central_center[0], central_center[1]+0.11, 'Uniform noise',
				 horizontalalignment='center',
				 verticalalignment='bottom', color=color_cycle_blue3[0],
				 fontsize=8, zorder=300) 
Example 45
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def _number_per_dimension_rectangle(self):
		"""
		Plots an ellipse that indicates the number per dimension
		"""
		# N_x rectangle
		y0 = - self.limit + 2 * self.spacing[0]
		y1 = - self.limit

		# xy = (central_center[0] - spacing[0] / 2.,
		# 	  central_center[1] - spacing[1] / 2.)
		rectangle1=plt.Rectangle((y0, y1), self.spacing[0], 2*self.limit,
								 ec='none',
								 fc=color_cycle_blue3[0], lw=2)
		plt.gca().add_artist(rectangle1) 
Example 46
Project: Detection_and_Recognition_in_Remote_Sensing_Image   Author: whywhs   File: tester.py    Apache License 2.0 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            if score < threshold:
                continue
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 47
Project: Detection_and_Recognition_in_Remote_Sensing_Image   Author: whywhs   File: show_offset.py    Apache License 2.0 5 votes vote down vote up
def show_boxes_simple(bbox, color='r', lw=2):
    rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=lw)
    plt.gca().add_patch(rect) 
Example 48
Project: YOLO   Author: MashiMaroLjc   File: draw.py    MIT License 5 votes vote down vote up
def box_to_rect(box, color="blue", linewidth=3):
    """

    :param box: (x_min,y_min,x_max,y_max)
    :param color:
    :param linewidth:
    :return:
    """
    """convert an anchor box to a matplotlib rectangle"""
    return plt.Rectangle(
        (box[0], box[1]), box[2]-box[0], box[3]-box[1],
        fill=False, edgecolor=color, linewidth=linewidth) 
Example 49
Project: ble5-nrf52-mac   Author: tomasero   File: test_simplification.py    MIT License 5 votes vote down vote up
def test_hatch():
    fig, ax = plt.subplots()
    ax.add_patch(plt.Rectangle((0, 0), 1, 1, fill=False, hatch="/"))
    ax.set_xlim((0.45, 0.55))
    ax.set_ylim((0.45, 0.55)) 
Example 50
Project: ble5-nrf52-mac   Author: tomasero   File: test_legend.py    MIT License 5 votes vote down vote up
def test_hatching():
    fig, ax = plt.subplots()

    # Patches
    patch = plt.Rectangle((0, 0), 0.3, 0.3, hatch='xx',
                          label='Patch\ndefault color\nfilled')
    ax.add_patch(patch)
    patch = plt.Rectangle((0.33, 0), 0.3, 0.3, hatch='||', edgecolor='C1',
                          label='Patch\nexplicit color\nfilled')
    ax.add_patch(patch)
    patch = plt.Rectangle((0, 0.4), 0.3, 0.3, hatch='xx', fill=False,
                          label='Patch\ndefault color\nunfilled')
    ax.add_patch(patch)
    patch = plt.Rectangle((0.33, 0.4), 0.3, 0.3, hatch='||', fill=False,
                          edgecolor='C1',
                          label='Patch\nexplicit color\nunfilled')
    ax.add_patch(patch)

    # Paths
    ax.fill_between([0, .15, .3], [.8, .8, .8], [.9, 1.0, .9],
                    hatch='+', label='Path\ndefault color')
    ax.fill_between([.33, .48, .63], [.8, .8, .8], [.9, 1.0, .9],
                    hatch='+', edgecolor='C2', label='Path\nexplicit color')

    ax.set_xlim(-0.01, 1.1)
    ax.set_ylim(-0.01, 1.1)
    ax.legend(handlelength=4, handleheight=4)