1

I have to find squares in an image and then create a separate image of the detected square. So far, i am able to detect the square and get its contour in terms of four points.

Problem: When i create the image using ROI, i am getting the background also where the square is not present. I want to remove that area and want to keep only the area related to square.

skm
  • 5,015
  • 8
  • 43
  • 104
  • 1
    See the answer http://stackoverflow.com/questions/22093174/copying-non-rectangular-roi-opencv/22093257#22093257 – Haris Mar 07 '14 at 05:41

1 Answers1

3

You want to use a mask!

Create a black and white single-channel image (CV_U8C1). The white part is the desired area (your region of interest, ROI) from the original image.

The vector "ROI_Vertices" contains the vertices of the ROI. Fit a polygon around it (ROI_Poly), then fill it with white.

Afterwards use CopyTo to subtract your ROI from the image.

// ROI by creating mask for your trapecoid
// Create black image with the same size as the original    
Mat mask = cvCreateMat(480, 640, CV_8UC1); 
for(int i=0; i<mask.cols; i++)
    for(int j=0; j<mask.rows; j++)
        mask.at<uchar>(Point(i,j)) = 0;

// Create Polygon from vertices
vector<Point> ROI_Poly;
approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, true);

// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);                 

// Create new image for result storage
Mat resImage = cvCreateMat(480, 640, CV_8UC3);

// Cut out ROI and store it in resImage 
image->copyTo(resImage, mask);    

Thanks to this guy for providing me with all the information i needed two weeks ago, when i had the same problem!

Sebastian Schmitz
  • 1,884
  • 3
  • 21
  • 41