2016-07-06 76 views
0

我有一个由栅格单元格组成的封闭线,其中我知道索引(存储在列表中的每个单元格的col和raw)。名单就像是 -获取python中光栅化边界线内栅格文件的单元格索引

enter image description here

我想获得这个封闭线内的细胞的指标,并将其存储在一个单独的列表。我想在python中做到这一点。这里是一个图像更清晰:光栅分界线接近,这是实现自己的(幼稚)算法,这是我的第一个想法

enter image description here

+0

你确定,你要列出(边界内即细胞)所有内部的点?从第一张图片中的指数看来,这似乎可能是一个相当大的集合,可能太大而无法有效处理。如果你所需要的(后来)是一种测试成员资格的方法,那么最好逐个测试一下。 – PeterE

回答

0

的一种方式。另一方面,为什么重新发明轮子:

人们可以很容易地看到,问题可以被解释为黑色和白色(光栅/像素)图像。然后外部和内部区域形成背景(黑色),而边界是闭合(白色)循环。 (很显然,颜色也可以切换,但是现在我会在黑色上使用白色。)碰巧有一些相当复杂的python图像处理库,即skimage,ndimagemahotas

我不是专家,但我认为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)