I don't know if exist a magic way to to this but you could try with contours.
- Extract the outer profile segments as a contours
- For each contour end point (pt0) search a contour that start around a current end point (pt1)
- You got the space as pt0->pt1 and that is 1st side of your rectangle
- Calculate the angle pt0->pt1
- Search the inner profile in angle+90 and angle-90 to get 3rd and 4th point of your rectangle. (Or align the a small area of the image arounf pt0 and pt1 and search the inner profile up and down)