python - Using masks to apply different thresholds to different parts of an image -
i have image, in want threshold part of image within circular region, , remainder of image outside of region.
unfortunately attempts seem thresholding image whole, ignoring masks. how can achieved? see code attempt below.
def circular_mask(h, w, centre=none, radius=none): if centre none: # use middle of image centre = [int(w / 2), int(h / 2)] if radius none: # use smallest distance between centre , image walls radius = min(centre[0], centre[1], w - centre[0], h - centre[1]) y, x = np.ogrid[:h, :w] dist_from_centre = np.sqrt((x - centre[0]) ** 2 + (y - centre[1]) ** 2) mask = dist_from_centre <= radius return mask img = cv2.imread('image.png', 0) #read image h,w = img.shape[:2] mask = circular_mask(h,w, centre=(135,140),radius=75) #create boolean circle mask mask_img = img.copy() inside = np.ma.array(mask_img, mask=~mask) t1 = inside < 50 #threshold part of image within circle, ignore rest of image plt.imshow(inside) plt.imshow(t1, alpha=.25) plt.show() outside = np.ma.array(mask_img, mask=mask) t2 = outside < 20 #threshold image outside circle region, ignoring image in circle plt.imshow(outside) plt.imshow(t2, alpha=.25) plt.show() fin = np.logical_or(t1, t2) #combine results both thresholds plt.imshow(fin) plt.show()
working solution:
img = cv2.imread('image.png', 0) h,w = img.shape[:2] mask = circular_mask(h,w, centre=(135,140),radius=75) inside = img.copy()*mask t1 = inside < 50#get_threshold(inside, 1) plt.imshow(inside) plt.show() outside = img.copy()*~mask t2 = outside < 70 plt.imshow(outside) plt.show() plt.imshow(t1) plt.show() plt.imshow(t2) plt.show() plt.imshow(np.logical_and(t1,t2)) plt.show()
i assume image single layered (e.g. grey scale). can make 2 copies of image. multiply (or logical and) mask 1 of them , invert of mask other one. apply desired threshold each of them. in end merge both images using logical or operation.
Comments
Post a Comment