2

我有一个图像,我想在一个圆形区域内对图像的一部分进行阈值处理,然后在该区域之外对图像的其余部分进行阈值处理。

不幸的是,我的尝试似乎是对整个图像进行阈值处理,而忽略了蒙版。如何正确实现这一目标?请参阅下面的代码尝试。

def circular_mask(h, w, centre=None, radius=None):
    if centre is None:  # use the middle of the image
        centre = [int(w / 2), int(h / 2)]
    if radius is None:  # use the smallest distance between the centre and 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 a boolean circle mask
mask_img = img.copy()

inside = np.ma.array(mask_img, mask=~mask)
t1 = inside < 50 #threshold part of image within the 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 the results from both thresholds together
plt.imshow(fin)
plt.show()

工作解决方案:

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()
4

1 回答 1

0

我假设您的图像是单层的(例如灰度)。您可以制作 2 个图像副本。将您的掩码与其中一个相乘(或逻辑与),然后将该掩码与另一个掩码反转。现在将您想要的阈值应用于它们中的每一个。最后使用逻辑或操作合并两个图像。

于 2017-08-15T06:10:15.970 回答