My project need to crop the image automatically to remove the white space around the drawing (Lattice).
Here is my code
grayImage = grayImage.ThresholdBinary(new Gray(threshold), new Gray(255));
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
CvInvoke.FindContours(grayImage, contours, null, RetrType.External, ChainApproxMethod.ChainApproxSimple);
for (int i = 0; i < contours.Size; i++)
{
Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
if (rect.Width > minWidth && rect.Height > minHeight)
{
CvInvoke.DrawContours(image, contours, i, new MCvScalar(255, 0, 0), 2);
}
}
imageBox.Image = image;
The main issue is that
FindContours
finds white contours, and the image background is white.We use
ThresholdBinaryInv
instead ofThresholdBinary
.ThresholdBinaryInv
applies threshold and invert black and white after applying the threshold (the pattern is going to be white on black instead of black on white).Code sample:
Result: