【发布时间】:2019-12-01 23:10:27
【问题描述】:
我正在尝试使用 SLIC 变体进行语义分割,并希望根据可用的基于点的注释为每个片段着色(根据其类)为原始图像创建一个掩码。如果该段中没有基于点的注释,则 leave 为 0。
我目前有一个图像的 x、y 点及其相关标签,以及一个查找和着色所需片段的(慢)方法。我熟悉矢量化或“pythonic”是做事,但我似乎无法加快最后一个 for 循环,并希望得到一些关于优化的建议或参考。谢谢。
# Point-based annotations
annotation = pd.read_csv("a_dataframe.csv") # [X, Y, Label]
color_label = {'class 1' : 25, 'class 2' : 50, 'class 3' : 75}
# Uses CPU to create single segmented image with current params
slic = SlicAvx2(num_components = n_segments, compactness = n_compactness)
segmented_image = slic.iterate(cv2.cvtColor(each_image, cv2.COLOR_RGB2LAB))
# Finds the segments of interest and records their ID
X = np.array(each_annotation.iloc[:, 0], dtype = 'uint8')
Y = np.array(each_annotation.iloc[:, 1], dtype = 'uint8')
L = np.array(each_annotation.iloc[:, 2], dtype = 'str') # Labels
DS = segmented_image[X, Y] # Desired Segments
# Empty mask, marks the segments of interest with the classes of the point in them
mask = np.zeros(each_image.shape[:2], dtype = "uint8")
# Would ideally like to find a more quickly way of doing this
for (index, segVal) in enumerate(DS):
mask[segmented_image == segVal] = color_label.get(L[index])
我基本上有我想用这里替换那个循环的东西:
[mask[segmented_image == s] for i, s in enumerate(DS)]
但我无法在mask 中使用适当的标签分配 X、Y 位置。我以为会是这样的:
[mask[segmented_image == s] for i, s in enumerate(DS)] = color_label.get(L[i])
但似乎我正在尝试为我正在生成的列表分配一个颜色值...
【问题讨论】:
-
您不能将该 for 循环转换为列表理解,因为它不构造列表。此外,列表推导并不比 for 循环快多少,因为循环中的大部分时间不是用于迭代,而是用于执行操作。 (列表推导在迭代构建新列表时节省了非常少的时间,但这不是您在这里所做的。)
-
嘿@Tomothy32,我明白你的意思here。我对列表理解是什么感到困惑。感谢您的反馈。
标签: python-3.x vectorization image-segmentation scikit-image superpixels