6

輪郭を見つけた画像がありますがskimage.measure.find_contours()、最大の閉じた輪郭の完全に外側にあるピクセルのマスクを作成したいと考えています。これを行う方法はありますか?

ドキュメントの例を変更します。

import numpy as np
import matplotlib.pyplot as plt
from skimage import measure

# Construct some test data
x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j]
r = np.sin(np.exp((np.sin(x)**2 + np.cos(y)**2)))

# Find contours at a constant value of 0.8
contours = measure.find_contours(r, 0.8)

# Select the largest contiguous contour
contour = sorted(contours, key=lambda x: len(x))[-1]

# Display the image and plot the contour
fig, ax = plt.subplots()
ax.imshow(r, interpolation='nearest', cmap=plt.cm.gray)
X, Y = ax.get_xlim(), ax.get_ylim()
ax.step(contour.T[1], contour.T[0], linewidth=2, c='r')
ax.set_xlim(X), ax.set_ylim(Y)
plt.show()

赤の輪郭は次のとおりです。

ここに画像の説明を入力

しかし、ズームインすると、輪郭がピクセルの解像度ではないことに注意してください。

ここに画像の説明を入力

ピクセルが完全に外側にある (つまり、等高線が交差していない) マスクを使用して、元の画像と同じ寸法の画像を作成するにはどうすればよいですか? 例えば

from numpy import ma
masked_image = ma.array(r.copy(), mask=False)
masked_image.mask[pixels_outside_contour] = True

ありがとう!

4

3 に答える 3

5

少し遅いですが、あなたはことわざを知っています。これが私がこれを達成する方法です。

import scipy.ndimage as ndimage    

# Create an empty image to store the masked array
r_mask = np.zeros_like(r, dtype='bool')

# Create a contour image by using the contour coordinates rounded to their nearest integer value
r_mask[np.round(contour[:, 0]).astype('int'), np.round(contour[:, 1]).astype('int')] = 1

# Fill in the hole created by the contour boundary
r_mask = ndimage.binary_fill_holes(r_mask)

# Invert the mask since you want pixels outside of the region
r_mask = ~r_mask

ここに画像の説明を入力

于 2018-09-21T11:42:36.867 に答える