Python cv2.boxPoints() Examples

The following are 30 code examples of cv2.boxPoints(). 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 also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: ChickenVision.py    From ChickenVision with MIT License 13 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
Source File: transforms_rbbox.py    From AerialDetection with Apache License 2.0 7 votes vote down vote up
def mask2poly_single(binary_mask):
    """

    :param binary_mask:
    :return:
    """
    try:
        contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        # contour_lens = np.array(list(map(len, contours)))
        # max_id = contour_lens.argmax()
        # max_contour = contours[max_id]
        max_contour = max(contours, key=len)
        rect = cv2.minAreaRect(max_contour)
        poly = cv2.boxPoints(rect)
        # poly = TuplePoly2Poly(poly)
    except:
        import pdb
        pdb.set_trace()
    return poly 
Example #3
Source File: coordinate_convert.py    From RetinaNet_Tensorflow_Rotation with MIT License 6 votes vote down vote up
def forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x_c, y_c, w, h, theta]
    :return: format [x1, y1, x2, y2, x3, y3, x4, y4]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7], rect[5]])
    else:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7]])

    return np.array(boxes, dtype=np.float32) 
Example #4
Source File: coordinate_convert.py    From R3Det_Tensorflow with MIT License 6 votes vote down vote up
def forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x_c, y_c, w, h, theta]
    :return: format [x1, y1, x2, y2, x3, y3, x4, y4]
    """

    boxes = []
    if with_label:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7], rect[5]])
    else:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7]])

    return np.array(boxes, dtype=np.float32) 
Example #5
Source File: siammask_tracker.py    From pysot with Apache License 2.0 6 votes vote down vote up
def _mask_post_processing(self, mask):
        target_mask = (mask > cfg.TRACK.MASK_THERSHOLD)
        target_mask = target_mask.astype(np.uint8)
        if cv2.__version__[-5] == '4':
            contours, _ = cv2.findContours(target_mask,
                                           cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
        else:
            _, contours, _ = cv2.findContours(target_mask,
                                              cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_NONE)
        cnt_area = [cv2.contourArea(cnt) for cnt in contours]
        if len(contours) != 0 and np.max(cnt_area) > 100:
            contour = contours[np.argmax(cnt_area)]
            polygon = contour.reshape(-1, 2)
            prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
            rbox_in_img = prbox
        else:  # empty mask
            location = cxy_wh_2_rect(self.center_pos, self.size)
            rbox_in_img = np.array([[location[0], location[1]],
                                    [location[0] + location[2], location[1]],
                                    [location[0] + location[2], location[1] + location[3]],
                                    [location[0], location[1] + location[3]]])
        return rbox_in_img 
Example #6
Source File: tools.py    From keras-ocr with MIT License 6 votes vote down vote up
def combine_line(line):
    """Combine a set of boxes in a line into a single bounding
    box.

    Args:
        line: A list of (box, character) entries

    Returns:
        A (box, text) tuple
    """
    text = ''.join([character if character is not None else '' for _, character in line])
    box = np.concatenate([coords[:2] for coords, _ in line] +
                         [np.array([coords[3], coords[2]])
                          for coords, _ in reversed(line)]).astype('float32')
    first_point = box[0]
    rectangle = cv2.minAreaRect(box)
    box = cv2.boxPoints(rectangle)

    # Put the points in clockwise order
    box = np.array(np.roll(box, -np.linalg.norm(box - first_point, axis=1).argmin(), 0))
    return box, text 
Example #7
Source File: coordinate_convert.py    From R2CNN-Plus-Plus_Tensorflow with MIT License 6 votes vote down vote up
def forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x_c, y_c, w, h, theta]
    :return: format [x1, y1, x2, y2, x3, y3, x4, y4]
    """
    boxes = []
    if with_label:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7], rect[5]])
    else:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7]])

    return np.array(boxes, dtype=np.float32) 
Example #8
Source File: mlt17_to_voc.py    From tf_ctpn with MIT License 6 votes vote down vote up
def test():
    # p1 = Point(5, 1)
    # p2 = Point(1, 4)
    # l1 = Line(p2, p1)
    # print(l1.k)
    #
    # p1 = Point(5, 4)
    # p2 = Point(1, 1)
    # l1 = Line(p1, p2)
    # print(l1.k)

    pnts = [(40, 40), (140, 85), (140, 160), (50, 100)]
    img = np.zeros((200, 200, 3))
    a = cv2.minAreaRect(np.asarray(pnts))

    img = cv2.line(img, pnts[0], pnts[1], (0, 255, 0), thickness=1)
    img = cv2.line(img, pnts[1], pnts[2], (0, 255, 0), thickness=1)
    img = cv2.line(img, pnts[2], pnts[3], (0, 255, 0), thickness=1)
    img = cv2.line(img, pnts[3], pnts[0], (0, 255, 0), thickness=1)

    box = cv2.boxPoints(a)

    def tt(p):
        return (p[0], p[1])

    img = cv2.line(img, tt(box[0]), tt(box[1]), (255, 255, 0), thickness=1)
    img = cv2.line(img, tt(box[1]), tt(box[2]), (255, 255, 0), thickness=1)
    img = cv2.line(img, tt(box[2]), tt(box[3]), (255, 255, 0), thickness=1)
    img = cv2.line(img, tt(box[3]), tt(box[0]), (255, 255, 0), thickness=1)

    cv2.imshow('test', img.astype(np.uint8))
    cv2.waitKey(0) 
Example #9
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 6 votes vote down vote up
def calcSafeRect(self, roi, src):
        '''
            return [x, y, w, h]
        '''
        box = cv2.boxPoints(roi)
        x, y, w, h = cv2.boundingRect(box)

        src_h, src_w, _ = src.shape

        tl_x = x if x > 0 else 0
        tl_y = y if y > 0 else 0
        br_x = x + w - 1 if x + w - 1 < src_w else src_w - 1
        br_y = y + h - 1 if y + h - 1 < src_h else src_h - 1

        roi_w = br_x - tl_x
        roi_h = br_y - tl_y
        if roi_w <= 0 or roi_h <= 0:
            return [tl_x, tl_y, roi_w, roi_h], False

        return [tl_x, tl_y, roi_w, roi_h], True 
Example #10
Source File: coordinate_convert.py    From remote_sensing_object_detection_2019 with MIT License 6 votes vote down vote up
def forward_convert(coordinate, with_label=True):
    """
    :param coordinate: format [x_c, y_c, w, h, theta]
    :return: format [x1, y1, x2, y2, x3, y3, x4, y4]
    """
    boxes = []
    if with_label:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7], rect[5]])
    else:
        for rect in coordinate:
            box = cv2.boxPoints(((rect[0], rect[1]), (rect[2], rect[3]), rect[4]))
            box = np.reshape(box, [-1, ])
            boxes.append([box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7]])

    return np.array(boxes, dtype=np.float32) 
Example #11
Source File: seg_detector_representer.py    From DBNet.pytorch with Apache License 2.0 6 votes vote down vote up
def get_mini_boxes(self, contour):
        bounding_box = cv2.minAreaRect(contour)
        points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])

        index_1, index_2, index_3, index_4 = 0, 1, 2, 3
        if points[1][1] > points[0][1]:
            index_1 = 0
            index_4 = 1
        else:
            index_1 = 1
            index_4 = 0
        if points[3][1] > points[2][1]:
            index_2 = 2
            index_3 = 3
        else:
            index_2 = 3
            index_3 = 2

        box = [points[index_1], points[index_2], points[index_3], points[index_4]]
        return box, min(bounding_box[1]) 
Example #12
Source File: TableRecognition.py    From OTR with GNU General Public License v3.0 6 votes vote down vote up
def compute_cell_hulls(self):
        """
        Run find_table_cell_polygons() and compute a rectangle enclosing the cell (for each cell).
        For most (4-point) cells, this is equivalent to the original path, however this removes
        small irregularities and extra points from larger, 5+-point cells (mostly merged cells)
        """
        self.compute_cell_polygons()
        # cv2 convexHull / minAreaRect only work with integer coordinates.
        self.cell_hulls = [
            cv2.boxPoints(cv2.minAreaRect(np.rint(self.cluster_coords[path]).astype(int)))
            for path in self.cell_polygons]
        # Compute centers of cell hulls
        self.cell_centers = np.zeros((len(self.cell_hulls), 2))
        for i in range(len(self.cell_hulls)):
            hull_points = self.cell_hulls[i]
            self.cell_centers[i] = cv_algorithms.meanCenter(hull_points) 
Example #13
Source File: mask_rcnn_with_text.py    From open_model_zoo with 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 #14
Source File: crop.py    From idmatch with 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 #15
Source File: siam_mask_tracker.py    From models with MIT License 6 votes vote down vote up
def _mask_post_processing(mask, center_pos, size, track_mask_threshold):
    target_mask = (mask > track_mask_threshold)
    target_mask = target_mask.astype(np.uint8)
    if cv2.__version__[-5] == '4':
        contours, _ = cv2.findContours(target_mask,
                                       cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_NONE)
    else:
        _, contours, _ = cv2.findContours(
                target_mask,
                cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cnt_area = [cv2.contourArea(cnt) for cnt in contours]
    if len(contours) != 0 and np.max(cnt_area) > 100:
        contour = contours[np.argmax(cnt_area)] 
        polygon = contour.reshape(-1, 2)
        prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
        rbox_in_img = prbox
    else:  # empty mask
        location = cxy_wh_2_rect(center_pos, size)
        rbox_in_img = np.array([[location[0], location[1]],
                    [location[0] + location[2], location[1]],
                    [location[0] + location[2], location[1] + location[3]],
                    [location[0], location[1] + location[3]]])
    return rbox_in_img 
Example #16
Source File: before_segmentation.py    From Printed-Text-recognition-and-conversion with 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 #17
Source File: class_PlateDetection.py    From ALPR_System with 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 #18
Source File: binarized_filter_result.py    From DVCNN_Lane_Detection with Apache License 2.0 5 votes vote down vote up
def __get_rrect_area(_rrect):
        """
        Get the area of the rotate rect
        :param _rrect:
        :return:
        """
        points = cv2.boxPoints(box=_rrect)
        firstline_length = math.sqrt(math.pow((points[1][0] - points[0][0]), 2) +
                                     math.pow((points[1][1] - points[0][1]), 2))
        secondline_length = math.sqrt(math.pow((points[2][0] - points[1][0]), 2) +
                                      math.pow((points[2][1] - points[1][1]), 2))
        return firstline_length*secondline_length 
Example #19
Source File: binarized_filter_result.py    From DVCNN_Lane_Detection with Apache License 2.0 5 votes vote down vote up
def __get_rrect_degree(_rrect):
        """
        Calculate the rotate degree of the rotate rect(angle between the longer side of the rotate rect and the x axis)
        :param _rrect: Rotate degree
        :return:
        """
        points = cv2.boxPoints(box=_rrect)
        firstline_length = math.pow((points[1][0] - points[0][0]), 2) + math.pow((points[1][1] - points[0][1]), 2)
        secondline_length = math.pow((points[2][0] - points[1][0]), 2) + math.pow((points[2][1] - points[1][1]), 2)

        if firstline_length > secondline_length:
            return FilterBinarizer.__calculate_line_degree(points[0], points[1])
        else:
            return FilterBinarizer.__calculate_line_degree(points[2], points[1]) 
Example #20
Source File: draw_box_in_img.py    From RetinaNet_Tensorflow_Rotation with 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 #21
Source File: fake_util.py    From CRAFT_keras with 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 
Example #22
Source File: util.py    From DBNet.pytorch with Apache License 2.0 5 votes vote down vote up
def expand_polygon(polygon):
    """
    对只有一个字符的框进行扩充
    """
    (x, y), (w, h), angle = cv2.minAreaRect(np.float32(polygon))
    if angle < -45:
        w, h = h, w
        angle += 90
    new_w = w + h
    box = ((x, y), (new_w, h), angle)
    points = cv2.boxPoints(box)
    return order_points_clockwise(points) 
Example #23
Source File: TableRecognition.py    From OTR with GNU General Public License v3.0 5 votes vote down vote up
def is_inside_table(polygon, reference):
    """
    Determine if a given polygon is fully located inside
    This works by checking if all polygon points are within (or on the edge of)
    the reference 

    returns True if and only if polygon is fully within or identical to the reference.
    """
    brect = cv2.boxPoints(cv2.minAreaRect(polygon))
    # All points need to be inside table corners
    for point in brect:
        if cv2.pointPolygonTest(reference, tuple(point), False) < 0:
            return False  # Not in contour
    return True 
Example #24
Source File: TableRecognition.py    From OTR with GNU General Public License v3.0 5 votes vote down vote up
def compute_contour_bounding_boxes(self):
        """
        Compute rotated min-area bounding boxes for every contour
        """
        self.contours_bbox = [None] * len(self.contours)
        self.aspect_ratios = np.zeros(self.size) # of rotated bounding boxes
        for i in range(len(self.contours)):
            if self.contours[i] is None: continue
            # Compute rotated bounding rectangle (4 points)
            bbox = cv2.minAreaRect(self.contours[i])
            # Compute aspect ratio
            (x1, y1), (x2, y2), angle = bbox
            self.aspect_ratios[i] = np.abs(x2 - x1) / np.abs(y2 - y1)
            # Convert to 4-point rotated box, convert to int and set as new contour
            self.contours_bbox[i] = np.rint(cv2.boxPoints(bbox)).astype(np.int) 
Example #25
Source File: card.py    From idmatch with MIT License 5 votes vote down vote up
def remove_borders(image):
    image = cv2.imread(image)
    orig = image.copy()
    ratio = image.shape[0] / 500.0
    image = resize(image, height=500)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray,(7,7),0)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    contrasted = clahe.apply(blur)
    im = Image.fromarray(contrasted)
    
    edged = cv2.Canny(blur, 20, 170)
    _, cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
    largest_area = 0
    for c in cnts:
        r = cv2.minAreaRect(c)
        area = r[1][0]*r[1][1]
        if area > largest_area:
            largest_area = area
            rect = r

    screenCnt = np.int0(cv2.boxPoints(rect))
    im = Image.fromarray(edged)

    cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
    im = Image.fromarray(image)

    if screenCnt is not None and len(screenCnt) > 0:
        return four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
    return orig 
Example #26
Source File: extract_candidate.py    From DVCNN_Lane_Detection with Apache License 2.0 5 votes vote down vote up
def __get_rrect_degree(_rrect):
        """
        Calculate the rotate degree of the rotate rect(angle between the longer side of the rotate rect and the x axis)
        :param _rrect: Rotate degree
        :return:
        """
        points = cv2.boxPoints(box=_rrect)
        firstline_length = math.pow((points[1][0] - points[0][0]), 2) + math.pow((points[1][1] - points[0][1]), 2)
        secondline_length = math.pow((points[2][0] - points[1][0]), 2) + math.pow((points[2][1] - points[1][1]), 2)

        if firstline_length > secondline_length:
            return RoiExtractor.__calculate_line_degree(points[0], points[1])
        else:
            return RoiExtractor.__calculate_line_degree(points[2], points[1]) 
Example #27
Source File: omr.py    From omr with 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
Source File: pdf-to-csv-cv.py    From pdf-to-csv-table-extactor with Do What The F*ck You Want To Public License 5 votes vote down vote up
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 #29
Source File: tgc_visualizer.py    From TGC-Designer-Tools with Apache License 2.0 5 votes vote down vote up
def drawBrushesOnImage(brushes, color, im, pc, image_scale, fill=True):
    for brush in brushes:
        center = pc.tgcToCV2(brush["position"]["x"], brush["position"]["z"], image_scale)
        center = (center[1], center[0]) # In point coordinates, not pixel
        width = brush["scale"]["x"] / image_scale
        height = brush["scale"]["z"] / image_scale
        rotation = - brush["rotation"]["y"] # Inverted degrees, cv2 bounding_box uses degrees

        thickness = 4
        if fill:
            thickness = -1 # Negative thickness is a filled ellipse

        brush_type_name = tgc_definitions.brushes.get(int(brush["type"]), "unknown")

        if 'square' in brush_type_name:
            box_points = cv2.boxPoints((center, (2.0*width, 2.0*height), rotation)) # Squares seem to be larger than circles
            box_points = np.int32([box_points]) # Bug with fillPoly, needs explict cast to 32bit

            if fill:
                cv2.fillPoly(im, box_points, color, lineType=cv2.LINE_AA)
            else:
                cv2.polylines(im, box_points, True, color, thickness, lineType=cv2.LINE_AA)
        else: # Draw as ellipse for now
            '''center – The rectangle mass center.
            size – Width and height of the rectangle.
            angle – The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.'''
            bounding_box =  (center, (1.414*width, 1.414*height), rotation) # Circles seem to scale according to radius
            cv2.ellipse(im, bounding_box, color, thickness=thickness, lineType=cv2.LINE_AA) 
Example #30
Source File: postprocessing.py    From open-solution-ship-detection with 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