Python numpy.int0() Examples

The following are 30 code examples for showing how to use numpy.int0(). These examples are extracted from open source projects. 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.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: ChickenVision   Author: team3997   File: ChickenVision.py    License: MIT License 11 votes vote down vote up
def getEllipseRotation(image, cnt):
    try:
        # Gets rotated bounding ellipse of contour
        ellipse = cv2.fitEllipse(cnt)
        centerE = ellipse[0]
        # Gets rotation of ellipse; same as rotation of contour
        rotation = ellipse[2]
        # Gets width and height of rotated ellipse
        widthE = ellipse[1][0]
        heightE = ellipse[1][1]
        # Maps rotation to (-90 to 90). Makes it easier to tell direction of slant
        rotation = translateRotation(rotation, widthE, heightE)

        cv2.ellipse(image, ellipse, (23, 184, 80), 3)
        return rotation
    except:
        # Gets rotated bounding rectangle of contour
        rect = cv2.minAreaRect(cnt)
        # Creates box around that rectangle
        box = cv2.boxPoints(rect)
        # Not exactly sure
        box = np.int0(box)
        # Gets center of rotated rectangle
        center = rect[0]
        # Gets rotation of rectangle; same as rotation of contour
        rotation = rect[2]
        # Gets width and height of rotated rectangle
        width = rect[1][0]
        height = rect[1][1]
        # Maps rotation to (-90 to 90). Makes it easier to tell direction of slant
        rotation = translateRotation(rotation, width, height)
        return rotation

#################### FRC VISION PI Image Specific ############# 
Example 2
Project: unmixing   Author: arthur-e   File: utils.py    License: MIT License 6 votes vote down vote up
def density_slice(rast, rel=np.less_equal, threshold=1000, nodata=-9999):
    '''
    Returns a density slice from a given raster. Arguments:
        rast        A gdal.Dataset or a NumPy array
        rel         A NumPy logic function; defaults to np.less_equal
        threshold   An integer number
    '''
    # Can accept either a gdal.Dataset or numpy.array instance
    if not isinstance(rast, np.ndarray):
        rastr = rast.ReadAsArray()

    else:
        rastr = rast.copy()

    if (len(rastr.shape) > 2 and min(rastr.shape) > 1):
        raise ValueError('Expected a single-band raster array')

    return np.logical_and(
        rel(rastr, np.ones(rast.shape) * threshold),
        np.not_equal(rastr, np.ones(rast.shape) * nodata)).astype(np.int0) 
Example 3
Project: oldnyc   Author: danvk   File: crop_morphology.py    License: Apache License 2.0 6 votes vote down vote up
def remove_border(contour, ary):
    """Remove everything outside a border contour."""
    # Use a rotated rectangle (should be a good approximation of a border).
    # If it's far from a right angle, it's probably two sides of a border and
    # we should use the bounding box instead.
    c_im = np.zeros(ary.shape)
    r = cv2.minAreaRect(contour)
    degs = r[2]
    if angle_from_right(degs) <= 10.0:
        box = cv2.cv.BoxPoints(r)
        box = np.int0(box)
        cv2.drawContours(c_im, [box], 0, 255, -1)
        cv2.drawContours(c_im, [box], 0, 0, 4)
    else:
        x1, y1, x2, y2 = cv2.boundingRect(contour)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4)

    return np.minimum(c_im, ary) 
Example 4
Project: Python-Code   Author: yzy1996   File: crop_morphology.py    License: MIT License 6 votes vote down vote up
def remove_border(contour, ary):
    """Remove everything outside a border contour."""
    # Use a rotated rectangle (should be a good approximation of a border).
    # If it's far from a right angle, it's probably two sides of a border and
    # we should use the bounding box instead.
    c_im = np.zeros(ary.shape)
    r = cv2.minAreaRect(contour)
    degs = r[2]
    if angle_from_right(degs) <= 10.0:
        box = cv2.cv.BoxPoints(r)
        box = np.int0(box)
        cv2.drawContours(c_im, [box], 0, 255, -1)
        cv2.drawContours(c_im, [box], 0, 0, 4)
    else:
        x1, y1, x2, y2 = cv2.boundingRect(contour)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4)

    return np.minimum(c_im, ary) 
Example 5
Project: PAN-Card-OCR   Author: dilippuri   File: crop_morphology.py    License: MIT License 6 votes vote down vote up
def remove_border(contour, ary):
    """Remove everything outside a border contour."""
    # Use a rotated rectangle (should be a good approximation of a border).
    # If it's far from a right angle, it's probably two sides of a border and
    # we should use the bounding box instead.
    c_im = np.zeros(ary.shape)
    r = cv2.minAreaRect(contour)
    degs = r[2]
    if angle_from_right(degs) <= 10.0:
        box = cv2.cv.BoxPoints(r)
        box = np.int0(box)
        cv2.drawContours(c_im, [box], 0, 255, -1)
        cv2.drawContours(c_im, [box], 0, 0, 4)
    else:
        x1, y1, x2, y2 = cv2.boundingRect(contour)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4)

    return np.minimum(c_im, ary) 
Example 6
Project: opencv-steel-darts   Author: hanneshoettinger   File: DartsRecognition.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getCorners(img_in):
    # number of features to track is a distinctive feature
    ## FeaturesToTrack important -> make accessible
    edges = cv2.goodFeaturesToTrack(img_in, 640, 0.0008, 1, mask=None, blockSize=3, useHarrisDetector=1, k=0.06)  # k=0.08
    corners = np.int0(edges)

    return corners 
Example 7
Project: open_model_zoo   Author: opencv   File: mask_rcnn_with_text.py    License: Apache License 2.0 6 votes vote down vote up
def masks_to_rects(masks):
        rects = []
        for mask in masks:
            decoded_mask = mask
            contours = cv2.findContours(decoded_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]

            areas = []
            boxes = []
            for contour in contours:
                area = cv2.contourArea(contour)
                areas.append(area)

                rect = cv2.minAreaRect(contour)
                box = cv2.boxPoints(rect)
                box = np.int0(box)
                boxes.append(box)

            if areas:
                i = np.argmax(areas)
                rects.append(boxes[i])

        return rects 
Example 8
Project: idmatch   Author: maddevsio   File: crop.py    License: MIT License 6 votes vote down vote up
def remove_border(contour, ary):
    """Remove everything outside a border contour."""
    # Use a rotated rectangle (should be a good approximation of a border).
    # If it's far from a right angle, it's probably two sides of a border and
    # we should use the bounding box instead.
    c_im = np.zeros(ary.shape)
    r = cv2.minAreaRect(contour)
    degs = r[2]
    if angle_from_right(degs) <= 10.0:
        box = cv2.boxPoints(r)
        box = np.int0(box)
        cv2.drawContours(c_im, [box], 0, 255, -1)
        cv2.drawContours(c_im, [box], 0, 0, 4)
    else:
        x1, y1, x2, y2 = cv2.boundingRect(contour)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1)
        cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4)

    return np.minimum(c_im, ary) 
Example 9
Project: R2CNN_Faster-RCNN_Tensorflow   Author: DetectionTeamUCAS   File: coordinate_convert.py    License: MIT License 5 votes vote down vote up
def back_forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x1, y1, x2, y2, x3, y3, x4, y4, (label)] 
    :param with_label: default True
    :return: format [x_c, y_c, w, h, theta, (label)]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = np.int0(rect[:-1])
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta, rect[-1]])

    else:
        for rect in coordinate:
            box = np.int0(rect)
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta])

    return np.array(boxes, dtype=np.float32) 
Example 10
Project: R2CNN_Faster-RCNN_Tensorflow   Author: DetectionTeamUCAS   File: show_box_in_tensor.py    License: MIT License 5 votes vote down vote up
def draw_box_with_color_rotate(img_batch, boxes, text):

    def draw_box_cv(img, boxes, text):
        img = img + np.array(cfgs.PIXEL_MEAN)
        boxes = boxes.astype(np.int64)
        img = np.array(img * 255 / np.max(img), np.uint8)
        for box in boxes:
            x_c, y_c, w, h, theta = box[0], box[1], box[2], box[3], box[4]
            rect = ((x_c, y_c), (w, h), theta)
            rect = cv2.boxPoints(rect)
            rect = np.int0(rect)
            color = (np.random.randint(255), np.random.randint(255), np.random.randint(255))
            cv2.drawContours(img, [rect], -1, color, 3)

        text = str(text)
        cv2.putText(img,
                    text=text,
                    org=((img.shape[1]) // 2, (img.shape[0]) // 2),
                    fontFace=3,
                    fontScale=1,
                    color=(255, 0, 0))

        img = img[:, :, ::-1]
        return img

    img_tensor = tf.squeeze(img_batch, 0)
    img_tensor_with_boxes = tf.py_func(draw_box_cv,
                                       inp=[img_tensor, boxes, text],
                                       Tout=[tf.uint8])

    img_tensor_with_boxes = tf.reshape(img_tensor_with_boxes, tf.shape(img_batch))

    return img_tensor_with_boxes 
Example 11
Project: seglink   Author: dengdan   File: seglink.py    License: GNU General Public License v3.0 5 votes vote down vote up
def bboxes_to_xys(bboxes, image_shape):
    """Convert Seglink bboxes to xys, i.e., eight points
    The `image_shape` is used to to make sure all points return are valid, i.e., within image area
    """
    if len(bboxes) == 0:
        return []
    
    assert np.ndim(bboxes) == 2 and np.shape(bboxes)[-1] == 5, 'invalid `bboxes` param with shape =  ' + str(np.shape(bboxes))
    
    h, w = image_shape[0:2]
    def get_valid_x(x):
        if x < 0:
            return 0
        if x >= w:
            return w - 1
        return x
    
    def get_valid_y(y):
        if y < 0:
            return 0
        if y >= h:
            return h - 1
        return y
    
    xys = np.zeros((len(bboxes), 8))
    for bbox_idx, bbox in enumerate(bboxes):
        bbox = ((bbox[0], bbox[1]), (bbox[2], bbox[3]), bbox[4])
        points = cv2.cv.BoxPoints(bbox)
        points = np.int0(points)
        for i_xy, (x, y) in enumerate(points):
            x = get_valid_x(x)
            y = get_valid_y(y)
            points[i_xy, :] = [x, y]
        points = np.reshape(points, -1)
        xys[bbox_idx, :] = points
    return xys 
Example 12
Project: unmixing   Author: arthur-e   File: utils.py    License: MIT License 5 votes vote down vote up
def cfmask(mask, mask_values=(1,2,3,4,255), nodata=-9999):
    '''
    Returns a binary mask according to the CFMask algorithm results for the
    image; mask has True for water, cloud, shadow, and snow (if any) and False
    everywhere else. More information can be found:
        https://landsat.usgs.gov/landsat-surface-reflectance-quality-assessment

    Landsat 4-7 Pre-Collection pixel_qa values to be masked:
        mask_values = (1, 2, 3, 4)

    Landsat 4-7 Collection 1 pixel_qa values to be masked (for "Medium" confidence):
        mask_values = (1, 68, 72, 80, 112, 132, 136, 144, 160, 176, 224)

    Landsat 8 Collection 1 pixel_qa values to be masked (for "Medium" confidence):
        mask_values = (1, 324, 328, 386, 388, 392, 400, 416, 432, 480, 832, 836, 840, 848, 864, 880, 900, 904, 912, 928, 944, 992, 1024)

    Arguments:
        mask        A gdal.Dataset or a NumPy array
        mask_path   The path to an EOS HDF4 CFMask raster
        mask_values The values in the mask that correspond to NoData pixels
        nodata      The NoData value; defaults to -9999.
    '''
    if not isinstance(mask, np.ndarray):
        maskr = mask.ReadAsArray()

    else:
        maskr = mask.copy()

    # Mask according to bit-packing described here:
    # https://landsat.usgs.gov/landsat-surface-reflectance-quality-assessment
    maskr = np.in1d(maskr.reshape((maskr.shape[0] * maskr.shape[1])), mask_values)\
        .reshape((1, maskr.shape[0], maskr.shape[1])).astype(np.int0)

    return maskr 
Example 13
Project: hazymaze   Author: guille0   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def crop_from_points(img, corners, make_square=False):

    cnt = np.array([corners[0], corners[1], corners[2], corners[3]])

    rect = cv2.minAreaRect(cnt)
    center, size, theta = rect

    # Angle correction
    if theta < -45:
        theta += 90
        cnt = np.array([corners[1], corners[3], corners[0], corners[2]])

        rect = (center, size, theta)
        box = cv2.boxPoints(rect)
        box = np.int0(box)

        height = int(rect[1][0])
        width = int(rect[1][1])
    else:
        rect = (center, size, theta)
        box = cv2.boxPoints(rect)
        box = np.int0(box)

        height = int(rect[1][1])
        width = int(rect[1][0])

    src_pts = np.float32([corners[0],corners[1],corners[2],corners[3]])
    dst_pts = np.float32([[0,0],[width,0],[0,height],[width,height]])

    M = cv2.getPerspectiveTransform(src_pts, dst_pts)
    warped = cv2.warpPerspective(img, M, (width, height))

    transformation_data = {
        'matrix': M,
        'original_shape': (height, width)
    }

    return warped, transformation_data 
Example 14
Project: R2CNN-Plus-Plus_Tensorflow   Author: DetectionTeamUCAS   File: coordinate_convert.py    License: MIT License 5 votes vote down vote up
def back_forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x1, y1, x2, y2, x3, y3, x4, y4, (label)] 
    :param with_label: default True
    :return: format [x_c, y_c, w, h, theta, (label)]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = np.int0(rect[:-1])
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta, rect[-1]])

    else:
        for rect in coordinate:
            box = np.int0(rect)
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta])

    return np.array(boxes, dtype=np.float32) 
Example 15
Project: R2CNN-Plus-Plus_Tensorflow   Author: DetectionTeamUCAS   File: show_box_in_tensor.py    License: MIT License 5 votes vote down vote up
def draw_box_with_color_rotate(img_batch, boxes, text):

    def draw_box_cv(img, boxes, text):
        img = img + np.array(cfgs.PIXEL_MEAN)
        boxes = boxes.astype(np.int64)
        img = np.array(img * 255 / np.max(img), np.uint8)
        for box in boxes:
            x_c, y_c, w, h, theta = box[0], box[1], box[2], box[3], box[4]
            rect = ((x_c, y_c), (w, h), theta)
            rect = cv2.boxPoints(rect)
            rect = np.int0(rect)
            color = (np.random.randint(255), np.random.randint(255), np.random.randint(255))
            cv2.drawContours(img, [rect], -1, color, 3)

        text = str(text)
        cv2.putText(img,
                    text=text,
                    org=((img.shape[1]) // 2, (img.shape[0]) // 2),
                    fontFace=3,
                    fontScale=1,
                    color=(255, 0, 0))

        img = img[:, :, ::-1]
        return img

    img_tensor = tf.squeeze(img_batch, 0)
    img_tensor_with_boxes = tf.py_func(draw_box_cv,
                                       inp=[img_tensor, boxes, text],
                                       Tout=[tf.uint8])

    img_tensor_with_boxes = tf.reshape(img_tensor_with_boxes, tf.shape(img_batch))

    return img_tensor_with_boxes 
Example 16
Project: R3Det_Tensorflow   Author: Thinklab-SJTU   File: mask_utils.py    License: MIT License 5 votes vote down vote up
def make_r_gt_mask(fet_h, fet_w, img_h, img_w, gtboxes):
    gtboxes = np.reshape(gtboxes, [-1, 6])  # [x, y, w, h, theta, label]

    areas = gtboxes[:, 2] * gtboxes[:, 3]
    arg_areas = np.argsort(-1 * areas)  # sort from large to small
    gtboxes = gtboxes[arg_areas]

    fet_h, fet_w = int(fet_h), int(fet_w)
    mask = np.zeros(shape=[fet_h, fet_w], dtype=np.int32)
    for a_box in gtboxes:
        # print(a_box)
        box = cv2.boxPoints(((a_box[0], a_box[1]), (a_box[2], a_box[3]), a_box[4]))
        box = np.reshape(box, [-1, ])
        label = a_box[-1]
        new_box = []
        for i in range(8):
            if i % 2 == 0:
                x = box[i]
                new_x = int(x * fet_w / float(img_w))
                new_box.append(new_x)
            else:
                y = box[i]
                new_y = int(y*fet_h/float(img_h))
                new_box.append(new_y)

        new_box = np.int0(new_box).reshape([4, 2])
        color = int(label)
        # print(type(color), color)
        cv2.fillConvexPoly(mask, new_box, color=color)
    # print (mask.dtype)
    return mask 
Example 17
Project: R3Det_Tensorflow   Author: Thinklab-SJTU   File: coordinate_convert.py    License: MIT License 5 votes vote down vote up
def backward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x1, y1, x2, y2, x3, y3, x4, y4, (label)]
    :param with_label: default True
    :return: format [x_c, y_c, w, h, theta, (label)]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = np.int0(rect[:-1])
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta, rect[-1]])

    else:
        for rect in coordinate:
            box = np.int0(rect)
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta])

    return np.array(boxes, dtype=np.float32) 
Example 18
Project: remote_sensing_object_detection_2019   Author: clw5180   File: coordinate_convert.py    License: MIT License 5 votes vote down vote up
def back_forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x1, y1, x2, y2, x3, y3, x4, y4, (label)] 
    :param with_label: default True
    :return: format [x_c, y_c, w, h, theta, (label)]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = np.int0(rect[:-1])
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta, rect[-1]])

    else:
        for rect in coordinate:
            box = np.int0(rect)
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta])

    return np.array(boxes, dtype=np.float32) 
Example 19
Project: remote_sensing_object_detection_2019   Author: clw5180   File: show_box_in_tensor.py    License: MIT License 5 votes vote down vote up
def draw_box_with_color_rotate(img_batch, boxes, text):

    def draw_box_cv(img, boxes, text):
        img = img + np.array(cfgs.PIXEL_MEAN)
        boxes = boxes.astype(np.int64)
        img = np.array(img * 255 / np.max(img), np.uint8)
        for box in boxes:
            x_c, y_c, w, h, theta = box[0], box[1], box[2], box[3], box[4]
            rect = ((x_c, y_c), (w, h), theta)
            rect = cv2.boxPoints(rect)
            rect = np.int0(rect)
            color = (np.random.randint(255), np.random.randint(255), np.random.randint(255))
            cv2.drawContours(img, [rect], -1, color, 3)

        text = str(text)
        cv2.putText(img,
                    text=text,
                    org=((img.shape[1]) // 2, (img.shape[0]) // 2),
                    fontFace=3,
                    fontScale=1,
                    color=(255, 0, 0))

        img = img[:, :, ::-1]
        return img

    img_tensor = tf.squeeze(img_batch, 0)
    img_tensor_with_boxes = tf.py_func(draw_box_cv,
                                       inp=[img_tensor, boxes, text],
                                       Tout=[tf.uint8])

    img_tensor_with_boxes = tf.reshape(img_tensor_with_boxes, tf.shape(img_batch))

    return img_tensor_with_boxes 
Example 20
Project: RetinaNet_Tensorflow_Rotation   Author: DetectionTeamUCAS   File: coordinate_convert.py    License: MIT License 5 votes vote down vote up
def backward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x1, y1, x2, y2, x3, y3, x4, y4, (label)]
    :param with_label: default True
    :return: format [x_c, y_c, w, h, theta, (label)]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = np.int0(rect[:-1])
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta, rect[-1]])

    else:
        for rect in coordinate:
            box = np.int0(rect)
            box = box.reshape([4, 2])
            rect1 = cv2.minAreaRect(box)

            x, y, w, h, theta = rect1[0][0], rect1[0][1], rect1[1][0], rect1[1][1], rect1[2]
            boxes.append([x, y, w, h, theta])

    return np.array(boxes, dtype=np.float32) 
Example 21
Project: RetinaNet_Tensorflow_Rotation   Author: DetectionTeamUCAS   File: draw_box_in_img.py    License: MIT License 5 votes vote down vote up
def draw_a_rectangel_in_img(draw_obj, box, color, width, method):
    '''
    use draw lines to draw rectangle. since the draw_rectangle func can not modify the width of rectangle
    :param draw_obj:
    :param box: [x1, y1, x2, y2]
    :return:
    '''
    if method == 0:
        x1, y1, x2, y2 = box[0], box[1], box[2], box[3]
        top_left, top_right = (x1, y1), (x2, y1)
        bottom_left, bottom_right = (x1, y2), (x2, y2)

        draw_obj.line(xy=[top_left, top_right],
                      fill=color,
                      width=width)
        draw_obj.line(xy=[top_left, bottom_left],
                      fill=color,
                      width=width)
        draw_obj.line(xy=[bottom_left, bottom_right],
                      fill=color,
                      width=width)
        draw_obj.line(xy=[top_right, bottom_right],
                      fill=color,
                      width=width)
    else:
        x_c, y_c, w, h, theta = box[0], box[1], box[2], box[3], box[4]
        rect = ((x_c, y_c), (w, h), theta)
        rect = cv2.boxPoints(rect)
        rect = np.int0(rect)
        draw_obj.line(xy=[(rect[0][0], rect[0][1]), (rect[1][0], rect[1][1])],
                      fill=color,
                      width=width)
        draw_obj.line(xy=[(rect[1][0], rect[1][1]), (rect[2][0], rect[2][1])],
                      fill=color,
                      width=width)
        draw_obj.line(xy=[(rect[2][0], rect[2][1]), (rect[3][0], rect[3][1])],
                      fill=color,
                      width=width)
        draw_obj.line(xy=[(rect[3][0], rect[3][1]), (rect[0][0], rect[0][1])],
                      fill=color,
                      width=width) 
Example 22
Project: open-solution-ship-detection   Author: minerva-ml   File: postprocessing.py    License: MIT License 5 votes vote down vote up
def mask_to_bbox(mask):
    img_box = np.zeros_like(mask)
    _, cnt, _ = cv2.findContours(mask, 1, 2)
    rect = cv2.minAreaRect(cnt[0])
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(img_box, [box], 0, 1, -1)
    return img_box 
Example 23
Project: katarina   Author: robotika   File: navbox.py    License: MIT License 5 votes vote down vote up
def detectRoundel( frame, debug=False ):
    global g_mser
    global THRESHOLD_FRACTION
    if g_mser == None:
        g_mser = cv2.MSER( _delta = 10, _min_area=100, _max_area=300*50*2 )
    gray = cv2.cvtColor( frame, cv2.COLOR_BGR2GRAY )
    contours = g_mser.detect(gray, None)
    rectangles = []
    circles = []
    for cnt in contours:
        rect = cv2.minAreaRect(cnt)
        area = len(cnt) # MSER returns all points within area, not boundary points
        rectangleArea = float(rect[1][0]*rect[1][1])
        rectangleAspect = max(rect[1][0], rect[1][1]) / float(min(rect[1][0], rect[1][1]))
        if area/rectangleArea > 0.70 and rectangleAspect > 3.0:
            (x,y),(w,h),angle = rect
            rectangles.append( ((int(x+0.5),int(y+0.5)), (int(w+0.5),int(h+0.5)), int(angle)) )
        cir = cv2.minEnclosingCircle(cnt)
        (x,y),radius = cir
        circleArea = math.pi*radius*radius
        if area/circleArea > 0.64:
            circles.append( ((int(x+0.5),int(y+0.5)),int(radius+0.5)) )
    rectangles = removeDuplicities( rectangles )
    result = matchCircRect( circles=circles, rectangles=rectangles )
    if debug:
        for rect in rectangles:
            box = cv2.cv.BoxPoints(rect)
            box = np.int0(box)
            cv2.drawContours( frame,[box],0,(255,0,0),2)
        for cir in circles:
            (x,y),radius = cir
            center = (int(x),int(y))
            radius = int(radius)
            cv2.circle(frame, center, radius, (0,255,0), 2)
        if result:
            (x1,y1),(x2,y2) = result
            cv2.line(frame, (int(x1),int(y1)), (int(x2),int(y2)), (0,0,255), 3)
    return result 
Example 24
def extract_main_table(gray_image):
    inverted = cv2.bitwise_not(gray_image)
    blurred = cv2.GaussianBlur(inverted, (5, 5), 0)

    thresholded = cv2.threshold(blurred, 0, 255,
                                cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

    if DEBUG:
        show_wait_destroy("thresholded",thresholded)

    cnts = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[1]# if imutils.is_cv2() else cnts[1]
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
    rect = cv2.minAreaRect(cnts[0])
    box = cv2.boxPoints(rect)
    box = np.int0(box)

    extracted = four_point_transform(gray_image.copy(), box.reshape(4, 2))

    if DEBUG:
        color_image = cv2.cvtColor(gray_image.copy(), cv2.COLOR_GRAY2BGR)
        cv2.drawContours(color_image,[box],0,(0,0,255),2)
        cv2.drawContours(color_image, [cnts[0]], -1, (0, 255, 0), 2)


    return extracted 
Example 25
Project: pixel_link   Author: ZJULearning   File: pixel_link.py    License: MIT License 5 votes vote down vote up
def rect_to_xys(rect, image_shape):
    """Convert rect to xys, i.e., eight points
    The `image_shape` is used to to make sure all points return are valid, i.e., within image area
    """
    h, w = image_shape[0:2]
    def get_valid_x(x):
        if x < 0:
            return 0
        if x >= w:
            return w - 1
        return x
    
    def get_valid_y(y):
        if y < 0:
            return 0
        if y >= h:
            return h - 1
        return y
    
    rect = ((rect[0], rect[1]), (rect[2], rect[3]), rect[4])
    points = cv2.cv.BoxPoints(rect)
    points = np.int0(points)
    for i_xy, (x, y) in enumerate(points):
        x = get_valid_x(x)
        y = get_valid_y(y)
        points[i_xy, :] = [x, y]
    points = np.reshape(points, -1)
    return points

# @util.dec.print_calling_in_short
# @util.dec.timeit 
Example 26
Project: Cirq   Author: quantumlib   File: approximate_equality_protocol_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_numpy_dtype_compatibility():
    i_a, i_b, i_c = 0, 1, 2
    i_types = [np.intc, np.intp, np.int0, np.int8, np.int16, np.int32, np.int64]
    for i_type in i_types:
        assert cirq.approx_eq(i_type(i_a), i_type(i_b), atol=1)
        assert not cirq.approx_eq(i_type(i_a), i_type(i_c), atol=1)
    u_types = [np.uint, np.uint0, np.uint8, np.uint16, np.uint32, np.uint64]
    for u_type in u_types:
        assert cirq.approx_eq(u_type(i_a), u_type(i_b), atol=1)
        assert not cirq.approx_eq(u_type(i_a), u_type(i_c), atol=1)

    f_a, f_b, f_c = 0, 1e-8, 1
    f_types = [np.float16, np.float32, np.float64]
    if hasattr(np, 'float128'):
        f_types.append(np.float128)
    for f_type in f_types:
        assert cirq.approx_eq(f_type(f_a), f_type(f_b), atol=1e-8)
        assert not cirq.approx_eq(f_type(f_a), f_type(f_c), atol=1e-8)

    c_a, c_b, c_c = 0, 1e-8j, 1j
    c_types = [np.complex64, np.complex128]
    if hasattr(np, 'complex256'):
        c_types.append(np.complex256)
    for c_type in c_types:
        assert cirq.approx_eq(c_type(c_a), c_type(c_b), atol=1e-8)
        assert not cirq.approx_eq(c_type(c_a), c_type(c_c), atol=1e-8) 
Example 27
Project: omr   Author: rbaron   File: omr.py    License: MIT License 5 votes vote down vote up
def get_bounding_rect(contour):
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)
    return np.int0(box) 
Example 28
Project: ALPR_System   Author: longphungtuan94   File: class_PlateDetection.py    License: Apache License 2.0 5 votes vote down vote up
def crop_rotated_contour(self, plate, rect):
        """
        Rotate the plate and crop the plate with its rotation
        """
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        W = rect[1][0]
        H = rect[1][1]
        
        Xs = [i[0] for i in box]
        Ys = [i[1] for i in box]
        x1 = min(Xs)
        x2 = max(Xs)
        y1 = min(Ys)
        y2 = max(Ys)
        
        angle = rect[2]
        if angle < (-45):
            angle += 90
            
        # Center of rectangle in source image
        center = ((x1 + x2)/2,(y1 + y2)/2)

        # Size of the upright rectangle bounding the rotated rectangle
        size = (x2-x1, y2-y1)
        M = cv2.getRotationMatrix2D((size[0]/2, size[1]/2), angle, 1.0)

        # Cropped upright rectangle
        cropped = cv2.getRectSubPix(plate, size, center)
        cropped = cv2.warpAffine(cropped, M, size)
        croppedW = H if H > W else W
        croppedH = H if H < W else W

        # Final cropped & rotated rectangle
        croppedRotated = cv2.getRectSubPix(cropped, (int(croppedW), int(croppedH)), (size[0]/2, size[1]/2))
        return croppedRotated 
Example 29
Project: Printed-Text-recognition-and-conversion   Author: ishita27   File: before_segmentation.py    License: MIT License 5 votes vote down vote up
def getTransformationMatrix(img):
	#input should be a binarized image - text white, bg black
	
	#Find all white pixels
	pts = np.empty([0,0])
	pts = cv2.findNonZero(img)

	#Get rotated rect of white pixels
	rect = cv2.minAreaRect(pts)
	
	# rect[0] has the center of rectangle, rect[1] has width and height, rect[2] has the angle
	# To draw the rotated box and save the png image, uncomment below
	drawrect = img.copy()
	drawrect = cv2.cvtColor(drawrect, cv2.COLOR_GRAY2BGR)
	box = cv2.boxPoints(rect)
	box = np.int0(box) # box now has four vertices of rotated rectangle
	cv2.drawContours(drawrect,[box],0,(0,0,255),10)
	cv2.imwrite('rotated_rect.png', drawrect)

	#Change rotation angle if the tilt is in another direction
	rect = list(rect)
	if (rect[1][0] < rect[1][1]): # rect.size.width > rect.size.height
		temp = list(rect[1])
		temp[0], temp[1] = temp[1], temp[0]
		rect[1] = tuple(temp)
		rect[2] = rect[2] + 90.0

	#convert rect back to numpy/tuple
	rect = np.asarray(rect)
	
	#Rotate the image according to the found angle
	rotated_image = np.empty([0,0])
	M = cv2.getRotationMatrix2D(rect[0], rect[2], 1.0)
	#img = cv2.warpAffine(img, M, (img.shape[1],img.shape[0]))

	#returns the transformation matrix for this rotation
	return M 
Example 30
Project: CRAFT_keras   Author: RubanSeven   File: fake_util.py    License: Apache License 2.0 5 votes vote down vote up
def find_box(marker_map):
    """
    Calculate the minimum enclosing rectangles.
    :param marker_map: Input 32-bit single-channel image (map) of markers.
    :return: A list of point.
    """
    boxes = list()
    marker_count = np.max(marker_map)
    for marker_number in range(2, marker_count + 1):
        marker_cnt = np.swapaxes(np.array(np.where(marker_map == marker_number)), axis1=0, axis2=1)[:, ::-1]
        rect = cv2.minAreaRect(marker_cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        boxes.append(box)
    return boxes