i'm trying to find coordinates of white regions in my image using python and OpenCV. this should be a simple task using erode => threshold => findContours.
this is my code:
th_er = cv2.erode(th, np.ones((15, 15), np.uint8))
th_er = cv2.bitwise_not(th_er)
contours, _ = cv2.findContours(th_er, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for cntr in contours:
x, y, w, h = cv2.boundingRect(cntr)
cv2.rectangle(th_er, (x, y), (x + w, y + h), (100, 100, 100), 5)
cv2.imshow('il', th_er)
cv2.waitKey()
my problem is that "findContours" is returning weird results like shown in the image here.
so, anyone encountered this behavior or knows any possible fix ?
here is the original image.
img = cv2.imread('try.jpg', 0) # (200, 1427)
img2 = cv2.imread('try.jpg', -1) # (200, 1427, 4)
# gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # <-- you can use this to convert into grayscale image and then feed it to cv2.erode(img2, .....)
th_er = cv2.erode(img, np.ones((15, 15), np.uint8))
th_er = cv2.bitwise_not(th_er)
contours, _ = cv2.findContours(th_er, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for cntr in contours:
x, y, w, h = cv2.boundingRect(cntr)
cv2.rectangle(img2, (x, y), (x + w, y + h), (200, 100, 100), 5)
plt.figure(figsize=(15,20))
plt.imshow(img2)
plt.show()
EDIT:
It works fine now.
th_er1 = 255-cv2.bitwise_not(th_er)
As I said object should be in white and background should be in black. You had vice versa of it. By subtracting 255, It will be now in correct format.
# img = cv2.imread('try.png', 0) # (200, 1427)
img = cv2.imread('try.png') # (200, 1427, 4)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # <-- you can use this to convert into grayscale image and then feed it to cv2.erode(img2, .....)
_, th = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY+ cv2.THRESH_OTSU)
th_er = cv2.erode(th, np.ones((15, 15), np.uint8))
th_er1 = 255-cv2.bitwise_not(th_er) # <----- here
contours, _ = cv2.findContours(th_er1, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for cntr in contours:
x, y, w, h = cv2.boundingRect(cntr)
cv2.rectangle(img, (x, y), (x + w, y + h), (200, 100, 100), 5)
plt.figure(figsize=(15,20))
plt.imshow(img)
plt.show()