Detect all black pixels inside a surrounded closed white area
How can i detect black pixels surrounded by closed white pixels?
Background outside shapes should not be considered.
See next two images: First image i would like to extract all black pixels inside the hallow shape because it's traped/surrounded by white, but image 2 have a opeing and in that case i don't need the pixels.
Image 3 shows the desired capture area in red
Image 3: Desired capture area from image1 in red.
Same pass on image 2 should return 0 pixels (No area detected)
Another example:
Input:
Needed area in red:
EDIT 1:
Image<Gray, byte> grayscale = ActualLayerImage.ToEmguImage();
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
Mat external = new Mat();
CvInvoke.FindContours(grayscale, contours, external, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple);
var arr = external.GetData();
for (int i = 0; i < contours.Size; i++)
{
if((int)arr.GetValue(0, i, 2) != -1) continue;
var r = CvInvoke.BoundingRectangle(contours[i]);
CvInvoke.Rectangle(grayscale, r, new MCvScalar(125), 10);
}
Code on different inputs:
Image 4: OK
Image 5: OK
Image 6: Not OK!
How to discard image6 cases?
EDIT 2: The solution:
Image<Gray, byte> grayscale = ActualLayerImage.ToEmguImage().ThresholdBinary(new Gray(127), new Gray(255) );
ActualLayerImage.ToEmguImage();
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
Mat external = new Mat();
CvInvoke.FindContours(grayscale, contours, external, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple);
var arr = external.GetData();
/*
* hierarchy[i][0]: the index of the next contour of the same level
* hierarchy[i][1]: the index of the previous contour of the same level
* hierarchy[i][2]: the index of the first child
* hierarchy[i][3]: the index of the parent
*/
for (int i = 0; i < contours.Size; i++)
{
if ((int)arr.GetValue(0, i, 2) != -1 || (int)arr.GetValue(0, i, 3) == -1) continue;
var r = CvInvoke.BoundingRectangle(contours[i]);
CvInvoke.Rectangle(grayscale, r, new MCvScalar(125), 5);
}