I am trying to understand your question but there are some naming issues here: ROI in openCV is a rectangular region that can be described, for instance, with Rect class:
int x=3, y=5, width=10, height=15;
Rect roi(x, y, width, height);
Mat m(100, 100, CV_8UC3);
m = Scalar(0);
m(roi) = 255;
What you show here looks like a mask that is not constraint to rectangular shape, for example:
Mat mask, img;
img = mask & img;
All shown mask segments touch the picture border at least once but if you want them to touch it from both sides you have too loop over the mask pixels, find pixels with min, max x (if touching left right borders) and if some of them aren’t 0, width-1 connect corresponding points with the border somehow (with a thin line?). And of course you have to loop over all your segments that you call roi (in the code below I just select a bottom half to work with lower segment):
Mat I = imread("roi.jpg", 0);
imshow("input", I);
int h=I.rows;
int w=I.cols;
//select lower half of the mask
Rect rect(0, h/2, w, h/2);
Mat I2 = I(rect).clone();
int xmin=w, xmax=0;
int ymin, ymax;
for (int i=0; i<I2.rows; i++) {
uchar* imgrow = I2.ptr<uchar>(i);
for (int j=0; j<I2.cols; j++) {
if (xmin>j){
xmin=j;
ymin=i;
}
if (xmax<j) {
xmax=j;
ymax=i;
}
}
}
cout<<Point(xmin, ymin)<<", "<<Point(xmax, ymax)<<endl;
if (xmin>0) {
// connect
}
if (xmax<I2.cols) {
// connect
}
waitKey(-1);
The code outputs two points: [24, 536], [1535, 409], and the first one has to be connected with the border somehow since its x!=0. For example, line(I2, [24, 536], [0, 536], ...)