Suppose you have the two rectangles
import numpy as np
rect1 = np.array([[[20,15],[210,30],[220,100],[20,100]]], np.int32)
rect2 = np.array([[[25, 180], [215, 215], [220, 285], [20, 295]]], np.int32)
You can compute the largest inscribed polygon with the largestinteriorrectangle package. They come as [x, y, width, height]
.
import largestinteriorrectangle as lir
lir1 = lir.lir(rect1) # array([20, 30, 191, 71])
lir2 = lir.lir(rect2) # array([23, 215, 193, 71])
Let's plot this:
import cv2 as cv
img = np.zeros((380, 240, 3), dtype = "uint8")
cv.polylines(img, [rect1], True, (0,0,255), 3)
cv.polylines(img, [rect2], True, (0,0,255), 3)
cv.rectangle(img, lir.pt1(lir1), lir.pt2(lir1), (255,0,0), 3)
cv.rectangle(img, lir.pt1(lir2), lir.pt2(lir2), (255,0,0), 3)
cv.imshow('Shapes', img)
cv.waitKey(0)
cv.destroyAllWindows()
The package uses the algorithm of this paper
Note that the package uses numbas just in time compilation (JIT). So the very first time you import largestinteriorrectangle
takes some time, but afterwards its blazingly fast
In your image, the blue rectangle don't touch the red polygon. So you would need to add 1
to x and y and substract 2
from width and height