How To Remove Border Components In Python 2.7 Using Opencv
I want to remove the components which are touching the border of the image. I'm using OpenCV 2.4.10 and Python 2.7. I have done HSV conversion and THRESHOLD_BINARY of the image, n
Solution 1:
There is no direct method in openCV to do that. You can write a function using the method floodFill and loop over for border pixels as seed points.
floodFill(dstImg,seed,Scalar (0));
where:
dstImg : Output with border removed.
seed : [(x,y) points] All the border co-ordinates
Scalar(0) : The color to be filled if a connected region towards a seed point is found. Hence (0) as your case is to fill it as black.
Sample:
int totalRows = srcImg.rows;
int totalCols = srcImg.cols;
int strt = 0, flg = 0;
int iRows = 0, jCols = 0;
while (iRows < srcImg.rows)
{
if (flg ==1)
totalRows = -1;
Point seed(strt,iRows);
iRows++;
floodFill(dstImg,seed,Scalar (0));
if (iRows == totalRows)
{
flg++;
iRows = 0;
strt = totalCols - 1;
}
}
Similarly do modify it for columns. Hope It helps.
Solution 2:
Not very elegant, but you could enclose each contour in a bounding rectangle and test whether the coordinates of this rectangle fall on or outside the boundary of the image (im)
for c in contours:
include = True
# omit this contour if it touches the edge of the image
x,y,w,h = cv2.boundingRect(c)
if x <= 1 or y <=1:
include = False
if x+w+1 >= im.shape[1] or y+h+1 >= im.shape[0]:
include = False
# draw the contour
if include == True:
cv2.drawContours(im, [c], -1, (255, 0, 255), 2)
Post a Comment for "How To Remove Border Components In Python 2.7 Using Opencv"