0
我有一個由柵格單元格組成的封閉線,其中我知道索引(存儲在列表中的每個單元格的col和raw)。名單就像是 -獲取python中光柵化邊界線內柵格文件的單元格索引
我想獲得這個封閉線內的細胞的指標,並將其存儲在一個單獨的列表。我想在python中做到這一點。這裏是一個圖像更清晰:光柵分界線接近,這是實現自己的(幼稚)算法,這是我的第一個想法
我有一個由柵格單元格組成的封閉線,其中我知道索引(存儲在列表中的每個單元格的col和raw)。名單就像是 -獲取python中光柵化邊界線內柵格文件的單元格索引
我想獲得這個封閉線內的細胞的指標,並將其存儲在一個單獨的列表。我想在python中做到這一點。這裏是一個圖像更清晰:光柵分界線接近,這是實現自己的(幼稚)算法,這是我的第一個想法
的一種方式。另一方面,爲什麼重新發明輪子:
人們可以很容易地看到,問題可以被解釋爲黑色和白色(光柵/像素)圖像。然後外部和內部區域形成背景(黑色),而邊界是閉合(白色)循環。 (很顯然,顏色也可以切換,但是現在我會在黑色上使用白色。)碰巧有一些相當複雜的python圖像處理庫,即skimage,ndimage和mahotas。
我不是專家,但我認爲skimage.draw.polygon
,skimage.draw.polygon_perimiter
是解決您的問題最簡單的方法。
我的實驗得出了以下:
import matplotlib.pyplot as plt
import numpy as np
from skimage.draw import polygon, polygon_perimeter
from skimage.measure import label, regionprops
# some test data
# I used the format that your input data is in
# These are 4+99*4 points describing the border of a 99*99 square
border_points = (
[[100,100]] +
[[100,100+i] for i in range(1,100)] +
[[100,200]] +
[[100+i,200] for i in range(1,100)] +
[[200,200]] +
[[200,200-i] for i in range(1,100)] +
[[200,100]] +
[[200-i,100] for i in range(1,100)]
)
# convert to numpy arrays which hold the x/y coords for all points
# repeat first point at the end to close polygon.
border_points_x = np.array([p[0] for p in border_points] + [border_points[0][0]])
border_points_y = np.array([p[1] for p in border_points] + [border_points[0][1]])
# empty (=black) 300x300 black-and-white image
image = np.zeros((300, 300))
# polygon() calculates the indices of a filled polygon
# one would expect this to be inner+border but apparently it is inner+border/2
# probably some kind of "include only the left/top half"
filled_rr, filled_cc = polygon(border_points_y, border_points_x)
# set the image to white at these points
image[filled_rr, filled_cc] = 1
# polygon_perimeter() calculates the indices of a polygon perimiter (i.e. border)
border_rr, border_cc = polygon_perimeter(border_points_y, border_points_x)
# exclude border, by setting it to black
image[border_rr, border_cc] = 0
# label() detects connected patches of the same color and enumerates them
# the resulting image has each of those regions filled with its index
label_img, num_regions = label(image, background=0, return_num=True)
# regionprops() takes a labeled image and computes some measures for each region
regions = regionprops(label_img)
inner_region = regions[0]
print("area", inner_region.area)
# expecting 9801 = 99*99 for inner
# this is what you want, the coords of all inner points
inner_region.coords
# print it
fig, ax = plt.subplots()
ax.imshow(image, cmap=plt.cm.gray)
你確定,你要列出(邊界內即細胞)所有內部的點?從第一張圖片中的指數看來,這似乎可能是一個相當大的集合,可能太大而無法有效處理。如果你所需要的(後來)是一種測試成員資格的方法,那麼最好逐個測試一下。 – PeterE