CV2 Find Contours detecting the floor and not my target

Viewed 161

I am trying to detect the black tape on the floor, but whenever I try to increase the threshold to stop it from detecting the ground all it does is stop detecting the tape. enter image description here

from cv2 import cv2
import numpy as np

img = cv2.imread('tape4.jpeg', cv2.IMREAD_UNCHANGED)

#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 100
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
#find contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#create an empty image for contours
img_contours = np.zeros(img.shape)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
#save image
cv2.imwrite('contours.png',img_contours) 
1 Answers

You may use Use cv2.THRESH_BINARY_INV instead of cv2.THRESH_BINARY for finding pixels below thresh instead of pixels above thresh.

The reason you are detecting the floor, is that cv2.threshold marks (with 255 value), the pixels above thresh.
You want to mark the dark pixels below thresh.
You can compute: thresh_img = 255 - thresh_img, or use cv2.THRESH_BINARY_INV (result is the same).

I also recommend using closing morphological operation, for removing clutter.

Code for finding the tape:

import cv2
import numpy as np

img = cv2.imread('tape4.jpeg', cv2.IMREAD_UNCHANGED)

#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 20 # Set thresh to very low value (the tape is almost black).
#get threshold image
# Use cv2.THRESH_BINARY_INV instead of cv2.THRESH_BINARY for finding pixels below thresh instead of pixels above thresh
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY_INV)

# Apply closing morphological operation
thresh_img = cv2.morphologyEx(thresh_img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (21,21)));

#find contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#create an empty image for contours
img_contours = np.zeros(img.shape)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
#save image
cv2.imwrite('contours.png',img_contours) 

Result:
enter image description here

For finding the tape, you can look for the largest contour within contours:

# Get contour with maximum area
c = max(contours, key=cv2.contourArea)
img_contours = np.zeros(img.shape)
cv2.drawContours(img_contours, [c], -1, (0,255,0), 3)

Result:
enter image description here

Related