I am working on a project that draws bounding box around the obtained heatmap of the predicted abnormal image in an image classification task. Although, the algorithm I currently have draws a bounding box, it is not ideal. In fact, bounding boxes are quite large than I expect. Here is my code:
orig_img = (heatmap.permute(1,2,0).cpu().numpy() * 255).astype(np.uint8)
orig_img = cv2.cvtColor(orig_img, cv2.COLOR_RGB2BGR)
grey_img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(grey_img,50, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for cnt in contours:
if len(cnt) > 100:
x,y,w,h = cv2.boundingRect(cnt)
or_img = (invTrans(inputs[j].cpu()).permute(1,2,0).cpu().numpy() * 255).astype(np.uint8)
or_img = cv2.cvtColor(or_img, cv2.COLOR_RGB2BGR)
cv2.rectangle(or_img, (x,y), (x+w, y+h), (250,0,0),4)
plt.imshow(or_img)
cv2.waitKey(0)
plt.show()
I tried different values for len(cnt)
but could not obtain the optimal one. This is an image I got:
This is the image I want:
I would appreciate any help from you, guys.
question from:
https://stackoverflow.com/questions/65947690/drawing-bounding-box-on-heatmap-using-cv2 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…