查找多边形内的最大矩形-Python

查找多边形内的最大矩形-Python,python,opencv,Python,Opencv,有没有一个简单的方法来最大限度地垂直矩形适合内部的形状?我正在使用OpenCV 这不是最有效的实现,但它很有效:) 我假设你指的是面积最大的矩形?可能重复的?你必须处理非凸多边形吗?@Miki NxN二进制矩阵问题没有映射。这是一个不同的问题。是的,是的。矩阵也可以是矩形的@康纳 topleft_corner = []; bottomright_corner = []; rectangle_heights= []; rectangle_areas = []; #lets start s

有没有一个简单的方法来最大限度地垂直矩形适合内部的形状?我正在使用OpenCV


这不是最有效的实现,但它很有效:)


我假设你指的是面积最大的矩形?可能重复的?你必须处理非凸多边形吗?@Miki NxN二进制矩阵问题没有映射。这是一个不同的问题。是的,是的。矩阵也可以是矩形的@康纳
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)