How can I do image processing operations only in ROI part of original image directly?

前端 未结 3 1642
遇见更好的自我
遇见更好的自我 2021-01-03 15:49

Is that possible by using OpenCV to do some image processing operations only in ROI part of original image?

I search some articles on Internet. Most of codes look li

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-03 16:22

    You can get the sub-image using one either a Rect or two Range (see OpenCV doc).

    Mat3b img = imread("path_to_image");
    

    img:

    Rect r(100,100,200,200);
    Mat3b roi3b(img(r));
    

    As long as you don't change image type you can work on roi3b. All changes will be reflected in the original image img:

    GaussianBlur(roi3b, roi3b, Size(), 10);
    

    img after blur:

    If you change type (e.g. from CV_8UC3 to CV_8UC1), you need to work on a deep copy, since a Mat can't have mixed types.

    Mat1b roiGray;
    cvtColor(roi3b, roiGray, COLOR_BGR2GRAY);
    threshold(roiGray, roiGray, 200, 255, THRESH_BINARY);
    

    You can always copy the results on the original image, taking care to correct the type:

    Mat3b roiGray3b;
    cvtColor(roiGray, roiGray3b, COLOR_GRAY2BGR);
    roiGray3b.copyTo(roi3b);
    

    img after threshold:

    Full code for reference:

    #include 
    using namespace cv;
    
    int main(void)
    {
        Mat3b img = imread("path_to_image");
    
        imshow("Original", img);
        waitKey();
    
        Rect r(100,100,200,200);
        Mat3b roi3b(img(r));
    
        GaussianBlur(roi3b, roi3b, Size(), 10);
    
        imshow("After Blur", img);
        waitKey();
    
        Mat1b roiGray;
        cvtColor(roi3b, roiGray, COLOR_BGR2GRAY);
    
        threshold(roiGray, roiGray, 200, 255, THRESH_BINARY);
    
        Mat3b roiGray3b;
        cvtColor(roiGray, roiGray3b, COLOR_GRAY2BGR);
        roiGray3b.copyTo(roi3b);
    
        imshow("After Threshold", img);
        waitKey();
    
        return 0;
    }
    

提交回复
热议问题