OpenCv 2.3 C - How to isolate object inside image

后端 未结 1 530
一整个雨季
一整个雨季 2020-11-27 16:09

i have an image like:

\"source\"

i want to remove the black rows and cols round the number. So i want

相关标签:
1条回答
  • 2020-11-27 17:08

    One way to do it is to simply execute the bounding box technique to detect the digit, as illustrated by the image below:

    enter image description here

    Since your image is already processed the bounding box technique I use is a lot simpler.

    After that procedure, all you really need to do is set the ROI (Region of Interest) of the original image to the area defined by the box to achieve the crop effect and isolate the object:

    enter image description here

    Notice that in the resulting image there is one extra row/column of pixels in the border that are not white. Well, they are not black either. That's because I didn't performed any threshold method to binarize the image to black and white. The code below demonstrates the bounding box technique being executed on a grayscale version of the image.

    This is pretty much the roadmap to achieve what you want. For educational purposes I'm sharing the code I wrote using the C++ interface of OpenCV. I'm sure you are capable of converting it to the C interface.

    #include <cv.h>
    #include <highgui.h>
    
    #include <vector>
    
    
    int main(int argc, char* argv[])
    {
        cv::Mat img = cv::imread(argv[1]);
    
        // Convert RGB Mat to GRAY
        cv::Mat gray;
        cv::cvtColor(img, gray, CV_BGR2GRAY);
    
        // Store the set of points in the image before assembling the bounding box
        std::vector<cv::Point> points;
        cv::Mat_<uchar>::iterator it = gray.begin<uchar>();
        cv::Mat_<uchar>::iterator end = gray.end<uchar>();
        for (; it != end; ++it)
        {
            if (*it) points.push_back(it.pos());
        }
    
        // Compute minimal bounding box
        cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
    
    // Draw bounding box in the original image (debug purposes)
    //cv::Point2f vertices[4];
    //box.points(vertices);
    //for (int i = 0; i < 4; ++i)
    //{
            //cv::line(img, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 1, CV_AA);
    //}
    //cv::imshow("box", img);
    //cv::imwrite("box.png", img);
    
        // Set Region of Interest to the area defined by the box
        cv::Rect roi;
        roi.x = box.center.x - (box.size.width / 2);
        roi.y = box.center.y - (box.size.height / 2);
        roi.width = box.size.width;
        roi.height = box.size.height;
    
        // Crop the original image to the defined ROI
        cv::Mat crop = img(roi);
        cv::imshow("crop", crop);
    
        cv::imwrite("cropped.png", crop);
        cvWaitKey(0);
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题