Better ways to create a rectangular mask by openCV

前端 未结 2 840
故里飘歌
故里飘歌 2021-02-02 12:28

Creating a mask in openCV

      /** result I want
          0 0 0 0 0 0 0 0
          0 0 0 0 0 0 0 0
          0 0 1 1 1 1 0 0
          0 0 1 1 1 1 0 0
                


        
2条回答
  •  孤独总比滥情好
    2021-02-02 12:57

    If some one is looking for creating a non rectangular mask and then to apply it on the image then have a look here :

    Mat& obtainIregularROI(Mat& origImag, Point2f topLeft, Point2f topRight, Point2f botLeft, Point2f botRight){
    
            static Mat black(origImag.rows, origImag.cols, origImag.type(), cv::Scalar::all(0));
            Mat mask(origImag.rows, origImag.cols, CV_8UC1, cv::Scalar(0));
            vector< vector >  co_ordinates;
            co_ordinates.push_back(vector());
            co_ordinates[0].push_back(topLeft);
            co_ordinates[0].push_back(botLeft);
            co_ordinates[0].push_back(botRight);
            co_ordinates[0].push_back(topRight);
            drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );
    
            origImag.copyTo(black,mask);
            return black;
        }
    

    "black" is the image where we will finally obtain the result by cropping out the irregular ROI from the original image.

     static Mat black(origImag.rows, origImag.cols, origImag.type(), cv::Scalar::all(0));
    

    The "mask" is a Mat, initialized as the same size of original image and filled with 0. Mat mask(origImag.rows, origImag.cols, CV_8UC1, cv::Scalar(0));

    Putting the coordinates in ANTICLOCKWISE direction

        vector< vector >  co_ordinates;
        co_ordinates.push_back(vector());
        co_ordinates[0].push_back(topLeft);
        co_ordinates[0].push_back(botLeft);
        co_ordinates[0].push_back(botRight);
        co_ordinates[0].push_back(topRight);
    

    Now generating the mask actually

    drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );
    

    At the end copy the masked portion/ROI from original image (origImag) and paste on the portion of ROI from the original image (using mask) into image named as "black"

    origImag.copyTo(black,mask);
    

提交回复
热议问题