I am trying to fit minimum bounding boxes to each of these "speckles" shown below. As part of the image processing pipeline, I use findContours to detect contours in my data, and then draw a minimum bounding box given an array of discovered contours.
The minimum bounding boxes are not very accurate - some features are clearly missed whereas others fail to completely "encapsulate" a full connected feature (and instead is segmented into several small minimum bounding boxes). I have played around with the retrieval modes (RETR_TREE shown below) and the contour approximation method (CHAIN_APPROX_TC89_L1 shown below), but could not find something I really liked. Can someone suggest a more robust strategy to capture these contours more accurately using OpenCV Python?
import numpy as np
import cv2
# load image from series of frames
for x in range(1, 20):
convolved = cv2.imread(x.jpg)
original = convolved.copy
#convert to grayscale
gray = cv2.cvtColor(convolved, cv2.COLOR_BGR2GRAY)
#find all contours in given frame, store in array
contours, hierarchy = cv2.findContours(gray,cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_L1)
boxArea = []
#draw minimum bounding box around each discovered contour
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 2 and area < 100:
rect = cv2.minAreaRect(cnt)
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)
cv2.drawContours(original,[box], 0, (128,255,0),1)
boxArea.append(area)
#save box-fitted image
cv2.imwrite('x_boxFitted.jpg', original)
cv2.waitKey(0)
** Edit: Per Sturkman's suggestion, drawing all possible contours seemed to cover all visually detectable features.
drawContours
method ? – Moritzcv2.drawContours( original, contours,-1, (0,0,255), 2)
to test drawing all contours – sturkmen