def get_new_cont(cnt):
hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)
if np.any(defects)==None:
return np.array(cnt,dtype=np.int32)
new_cont=[cnt[defects[0,0][0]][0], cnt[defects[0,0][1]][0]]
for i in range(defects.shape[0]):
s,e,f,d = defects[i,0]
start = cnt[s][0]
end = cnt[e][0]
far = cnt[f][0]
if i!=0:
if s!=defects[i-1,0][1]:
new_cont.append(start)
new_cont.append(end)
else:
new_cont.append(end)
return np.array(new_cont)
img = cv2.imread(maskpath)
img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
_,thresh_img = cv2.threshold(img_gray,245,255,cv2.THRESH_BINARY)
contours,_= cv2.findContours(thresh_img,2,1)
for cnt in contours:
new_cont = get_new_cont(cnt)
pts = new_cont.reshape((-1, 1, 2))
img = cv2.polylines(img,pts=[pts], isClosed=True, color=(0, 0, 200), thickness=2)
cv2.imwrite(maskpath.replace("mask",savepath),img)