如何在两条曲线差异段识别中纳入收敛/发散起始端点?
曲线差异段提取的端点扩展需求
现有两条曲线,已确定它们的发散、收敛关键点以及轨迹的公共点。当前使用代码可提取曲线存在差异的段,但需要将曲线发散或收敛的首个端点也纳入识别范围——即红色线条需延伸至黑色星号位置,同时填充青色段与第二个黑色星号之间的间隙。
当前代码片段
import numpy as np # 注意:原代码使用`range`作为变量名会覆盖Python内置函数,建议改为`range_arr` range_arr = np.zeros(streamline.shape[0]).astype("bool") range_arr[points_common] = True range_arr = ~range_arr i = np.arange(0, streamline.shape[0]) different = i[range_arr] indices = np.where(np.diff(different) > 1)[0] + 1 different = np.split(different, indices)
各变量取值
range_arr = np.array([ True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]) points_common = np.array([ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]) # 原代码输出的差异段 different = [np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), np.array([24])]
修改后的代码(包含端点扩展)
import numpy as np # 保留原逻辑并修复变量名冲突 range_arr = np.zeros(streamline.shape[0]).astype("bool") range_arr[points_common] = True range_arr = ~range_arr i = np.arange(0, streamline.shape[0]) different = i[range_arr] indices = np.where(np.diff(different) > 1)[0] + 1 different_segments = np.split(different, indices) # 扩展差异段,纳入相邻的公共端点(发散/收敛关键点) extended_segments = [] # 转成集合提升查询效率 points_common_set = set(points_common) max_idx = streamline.shape[0] - 1 for seg in different_segments: extended = [] # 添加段前的公共端点(如果存在) first_idx = seg[0] if first_idx > 0 and (first_idx - 1) in points_common_set: extended.append(first_idx - 1) # 添加原差异段的所有点 extended.extend(seg) # 添加段后的公共端点(如果存在) last_idx = seg[-1] if last_idx < max_idx and (last_idx + 1) in points_common_set: extended.append(last_idx + 1) # 转换为numpy数组存入结果 extended_segments.append(np.array(extended))
修改说明
- 修复了原代码中
range变量名覆盖Python内置函数的问题,改为range_arr - 将
points_common转换为集合,大幅提升端点归属的查询效率 - 对每个差异段进行双向扩展:
- 若段的起始点不是索引0,且前一个点属于公共点(收敛端点),则将该端点纳入
- 若段的结束点不是最后一个索引,且后一个点属于公共点(发散端点),则将该端点纳入
- 最终输出的
extended_segments会变成:
完全满足红色线条延伸至黑色星号、填充间隙的需求[np.array([0,1,2,3,4,5,6,7,8,9,10]), np.array([23,24,25])]
内容的提问来源于stack exchange,提问作者Määäx
相关产品推荐
相关产品推荐

