如何移除DM-Script中线段标注及关联长度文本并保留其他文本?
DM脚本移除带长度标签的线段及关联文本
在DM脚本处理图像时,添加带长度标签的线段会同时生成线段标注和显示长度的文本组件。需要移除这些线段标注及其关联文本,但保留其他所有文本组件。
现有仅移除线段标注的代码:
Void clear_line_annot(Image img) { Number k_line_annot = 2 ImageDisplay img_disp = img.ImageGetImageDisplay(0) Number comp_num = img_disp.ComponentCountChildren() for (Number i = comp_num - 1; i >= 0; i--) { Component comp = img_disp.ComponentGetChild(i) if (comp.ComponentGetType() != k_line_annot) Continue comp.ComponentRemoveFromParent() } } Image img := GetFrontImage() clear_line_annot(img)
问题1:识别并移除关联文本组件
DM中带长度标签的线段(类型常量k_line_annot=2)与对应长度文本(类型常量k_text_annot=1)通过组件关联机制绑定,可通过ComponentGetLinkedComponent()方法获取关联的文本组件。修改代码如下,实现同时移除线段及关联文本:
Void clear_line_with_label(Image img) { Number k_line_annot = 2 Number k_text_annot = 1 ImageDisplay img_disp = img.ImageGetImageDisplay(0) Number comp_num = img_disp.ComponentCountChildren() // 从后往前遍历,避免组件索引错乱 for (Number i = comp_num - 1; i >= 0; i--) { Component comp = img_disp.ComponentGetChild(i) if (comp.ComponentGetType() != k_line_annot) Continue // 获取并移除关联的文本组件 Component linked_text = comp.ComponentGetLinkedComponent() if (linked_text.ScriptObjectIsValid() && linked_text.ComponentGetType() == k_text_annot) { linked_text.ComponentRemoveFromParent() } // 移除线段组件 comp.ComponentRemoveFromParent() } } Image img := GetFrontImage() clear_line_with_label(img)
问题2:更优/高效的实现方法
上述遍历方式已具备高效性(从后往前遍历避免索引偏移),若需支持嵌套组件(如线段被分组到Group组件中),可使用递归遍历确保不遗漏任何深层的线段标注,同时不影响其他独立文本组件:
Void RemoveLineAndLabelRecursive(Component parent_comp) { Number k_line_annot = 2 Number k_text_annot = 1 Number child_count = parent_comp.ComponentCountChildren() for (Number i = child_count - 1; i >= 0; i--) { Component child = parent_comp.ComponentGetChild(i) Number child_type = child.ComponentGetType() if (child_type == k_line_annot) { // 移除关联文本 Component linked_text = child.ComponentGetLinkedComponent() if (linked_text.ScriptObjectIsValid() && linked_text.ComponentGetType() == k_text_annot) { linked_text.ComponentRemoveFromParent() } // 移除线段 child.ComponentRemoveFromParent() } // 递归处理嵌套子组件 else if (child.ComponentCountChildren() > 0) { RemoveLineAndLabelRecursive(child) } } } Void clear_line_with_label(Image img) { ImageDisplay img_disp = img.ImageGetImageDisplay(0) RemoveLineAndLabelRecursive(img_disp) } Image img := GetFrontImage() clear_line_with_label(img)
该递归版本覆盖了更多场景,且保持了高效性,仅处理线段及其关联文本,不会触动其他无关组件。
内容的提问来源于stack exchange,提问作者ChenZX
相关产品推荐
相关产品推荐

