微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何测试坐标是否在标签或蒙版内

如何解决如何测试坐标是否在标签或蒙版内

我正在尝试测试列表中的哪些点(numpy 数组或熊猫)在给定的布尔掩码(或标记图像)内。 我找到了与多边形进行比较但没有与蒙版进行比较的方法

从这个数据集示例中,我如何测试掩码内的坐标? (最好在 Pandas 中添加一列,说明它们属于哪个标签 - 那,或者在“coords”变量中添加一个新列,说明它属于哪个标签)。

蒙版/标签在我的实现中不会是矩形(基本上是单元格形状),我只是在这里这样做,因为它更容易。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# import numpy as np

coords = np.random.rand(40,2) *1024
mask = np.zeros((1024,1024))
mask[300:600,50:125] = 1
mask[700:800,400:650] = 2

plt.imshow(mask)
plt.scatter(coords[:,0],coords[:,1],color='red')

enter image description here

解决方法

您可以使用 NumPy 对掩码进行索引和稍加按摩后的坐标。

coords_int = np.round(coords).astype(int)  # or np.floor,depends
values_at_coords = mask[tuple(coords_int.T)]
points_per_value = np.bincount(values_at_coords)

现在 points_per_value 包含一个数组,使得 points_per_value[i] 包含落在掩码标签 i 中的坐标数。 (docs for np.bincount)

有关第二行的更多信息,您可以在 NumPy docs 中阅读有关 NumPy 整数数组索引的信息。

,
from collections import defaultdict
import matplotlib.pyplot as plt
coords = np.random.rand(40,2) *1024
mask = np.zeros((1024,1024))
mask[300:600,50:125] = 1
mask[700:800,400:650] = 2
plt.imshow(mask,origin='lower')
plt.scatter(coords[:,1],coords[:,0],color='red')
res = defaultdict(list)
for i in np.unique(mask)[1:]:
    temp = coords[(coords[:,0] >= (mask == i).nonzero()[0][0]) & (coords[:,0] <= (mask == i).nonzero()[0][-1])]
    res[i] = temp[(temp[:,1] >= (mask == i).nonzero()[1][0]) & (temp[:,1] <= (mask == i).nonzero()[1][-1])]
print(res)
,

您可以使用 shapely 来断言一个点是否在多边形内。

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

您的第一个掩码由以下多边形定义。

polygon = Polygon([(300,50),(300,125),(600,125)])

测试两个样本点。

point1 = Point(315,1200)
point2 = Point(315,75)
print(polygon.contains(point1)) #False
print(polygon.contains(point2)) #True

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。