def roiMask(image, boundaries):
scale = max([1.0, np.average(np.array(image.shape)[0:2] / 400.0)])
shape = (int(round(image.shape[1] / scale)), int(round(image.shape[0] / scale)))
small_color = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)
# reduce details and remove noise for better edge detection
small_color = cv2.bilateralFilter(small_color, 8, 64, 64)
small_color = cv2.pyrMeanShiftFiltering(small_color, 8, 64, maxLevel=1)
small = cv2.cvtColor(small_color, cv2.COLOR_BGR2HSV)
hue = small[::, ::, 0]
intensity = cv2.cvtColor(small_color, cv2.COLOR_BGR2GRAY)
edges = extractEdges(hue, intensity)
roi = roiFromEdges(edges)
weight_map = weightMap(hue, intensity, edges, roi)
_, final_mask = cv2.threshold(roi, 5, 255, cv2.THRESH_BINARY)
small = cv2.bitwise_and(small, small, mask=final_mask)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))
for (lower, upper) in boundaries:
lower = np.array([lower, 80, 50], dtype="uint8")
upper = np.array([upper, 255, 255], dtype="uint8")
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(small, lower, upper)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
final_mask = cv2.bitwise_and(final_mask, mask)
# blur the mask for better contour extraction
final_mask = cv2.GaussianBlur(final_mask, (5, 5), 0)
return (final_mask, weight_map, scale)
评论列表
文章目录