【问题标题】:Get cells indexes of raster file inside a rasterized border line in python在python中获取光栅化边界线内光栅文件的单元格索引
【发布时间】:2016-07-06 17:12:27
【问题描述】:

我有一条由栅格单元组成的闭合线,我知道其中的索引(存储在列表中的每个单元的 col 和 raw)。列表就像 -

我想获取此闭合行中单元格的索引并将它们存储在单独的列表中。我想在python中做到这一点。这是一个更清晰的图像:光栅边界线

【问题讨论】:

  • 您确定要列出所有内部点(即边界内的单元格)吗?从您第一张图片中给出的索引来看,这似乎是一个相当大的集合,可能太大而无法有效处理。如果您(以后)需要的只是一种测试成员资格的方法,那么最好逐个进行测试。

标签: python indexing polygon raster


【解决方案1】:

解决这个问题的一种方法是实现自己的(简单)算法,这是我的第一个想法。另一方面,为什么要重新发明轮子:

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

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

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2014-02-15
    • 1970-01-01
    • 2016-12-25
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    相关资源
    最近更新 更多