在多边形内找到最大的矩形 - Python

3

我假设你是指面积最大的矩形? - conner.xyz
可能是[在N×N二进制矩阵中查找仅包含零的最大矩形]的重复问题(https://dev59.com/J3E95IYBdhLWcg3wDpmg×n-binary-matrix) - Miki
1
你需要处理非凸多边形吗? - conner.xyz
@Miki NxN 二进制矩阵问题无法映射。这是一个不同的问题。 - conner.xyz
是的,可以。矩阵也可以是矩形的。@conner - Miki
2个回答

0

您可以使用largestinteriorrectangle包:

pip install largestinteriorrectangle

然后

import largestinteriorrectangle as lir
import cv2 as cv

grid = cv.imread("mask.png", 0)
grid = grid > 0
rect = lir.largest_interior_rectangle(grid)

0

这不是最有效的实现方法,但它可以工作 :)

topleft_corner = []; 
bottomright_corner = []; 
rectangle_heights= []; 
rectangle_areas = [];
#lets start scanning from the left
# and find the outer two points in each vertical line
for i in range(0,mask.shape[1]):
    line = mask[:,i]
    foreground_indecies = np.where(line == 255)

    top_p1 = foreground_indecies[0][0]
    bottom_p1 = foreground_indecies[0][-1]
    line1_length = bottom_p1 - top_p1
    #scan the mask fromt the right side
    for j in range(mask.shape[1]-1,i+2,-1):
        line2 = mask[:,j]
        foreground_indecies = np.where(line2 == 255)
        top_p2 = foreground_indecies[0][0]
        bottom_p2 = foreground_indecies[0][-1]
        #find length of right line
        line2_length = bottom_p2 - top_p2

        #If the two lines are equal then we have an upright rectangle  :)
        if line1_length == line2_length and i != j :
            topleft_corner.append([i,top_p1])
            bottomright_corner.append([j,bottom_p2])
            rectangle_heights.append(line1_length)
            rectangle_areas.append((j-i) *(line1_length))


#Now we have the list of all possible rectangle heights and their correpsonding pionts
#You can then decide how to choose the right rectangle
#A - By how far it extends vertically
#B - By area size
#I am going to demonstrate how to do B
max_area_index = np.argmax(np.array(rectangle_areas))
topleft_pt  = tuple(topleft_corner[max_area_index])
bottomright_pt= tuple(bottomright_corner[max_area_index])
rgb_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
color = (255, 0, 0) 
# Line thickness of 2 px 
thickness = 2 
# Using cv2.rectangle() method 
# Draw a rectangle with blue line borders of thickness of 2 px 
image = cv2.rectangle(rgb_mask, topleft_pt, bottomright_pt, color, thickness)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接