Search code examples
javaimageopencvjavacv

crop rectangle with certain border color and cetain background color JAVA


I have an Image with some rectangles inside it .. what i need is to crop only rectangles that have a red border and white background using (Java) or JavaCV.

for example i have an car image with license plate .. each letter at the license plate have red bordered rectangle around it and a white background.

what i am looking for is to crop each letter in a single image .. letters are identified by red bordered rectangle around each one and a white background.

Any suggestions? Thanks


Solution

    1. Change color space to HSV

       IplImage* imgHSV = cvCreateImage(cvGetSize(img), 8, 3);
       cvCvtColor(img, imgHSV, CV_BGR2HSV);
      
    2. Get only hue channel:

      cvSplit( imgHSV, h_plane, s_plane, v_plane, 0 );
      
    3. Do the thresholding to find red color:

      cvInRangeS(h_plane, cvScalar(x, x, x), cvScalar(x, x, x), imgThreshed);
      

      x - range of red in HSV color model.

      After this you will have white and black image, where white color is a red color on your original image (they should be of rectangle shape, as you said).

    4. Then use cvFindContours function.

      int contoursCont = cvFindContours( imgThreshed, storage,&contours,sizeof(CvContour),CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0));
      
    5. To bound box (rectangle) use (for every contour):

      CvBox2D box = cvMinAreaRect2( @current_contour@,
                              CvMemStorage* storage CV_DEFAULT(NULL))
      

      To check the color of background calculate its histogram and check if values of bins are only 255 and 0 (they are values of white and black colors).

    Hope, that will be useful!