You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复Centroid存储异常并拆分Pandas的Centroid列为Centroid_x与Centroid_y

问题修复方案

问题1:Centroid值错误存入其他字段

根源分析

代码存在三个关键问题:

  • output_file.write(',' + str(to_print))缩进错误,未包含在属性遍历的循环体内,导致每个区域仅写入最后一个属性(Centroid)的值,引发字段错位。
  • cluster_props['Label']应为小写cluster_props['label'](skimage.regionprops的属性名是小写格式)。
  • Centroid是元组类型,直接转字符串会生成带括号的格式,易引发CSV解析时的字段错位。

修复代码

from scipy import ndimage
from skimage import measure

# 假设mask、structure、image已提前定义
labeled_mask, num_labels = ndimage.label(mask, structure=s)
clusters = measure.regionprops(labeled_mask, image) 
propList = ['Area', 'MajorAxisLength', 'MinorAxisLength', 'Centroid']

# 使用with语句自动管理文件,避免手动关闭遗漏
with open('draft_Stelle_measurements.csv', 'w') as output_file:
    # 写入表头,增加Label列
    output_file.write('Label,' + ",".join(propList) + '\n')
    
    for cluster_props in clusters:
        output_line = [str(cluster_props['label'])]
        for prop in propList:
            if prop == 'Area':
                to_print = cluster_props[prop]
            elif prop == 'orientation':
                to_print = cluster_props[prop] * 57.2958
            elif 'Intensity' not in prop:
                # 处理Centroid时,将元组转为无括号的逗号分隔字符串
                if prop == 'Centroid':
                    to_print = f"{cluster_props[prop][0]},{cluster_props[prop][1]}"
                else:
                    to_print = cluster_props[prop]
            else:
                to_print = cluster_props[prop]
            output_line.append(str(to_print))
        # 一次性写入整行,避免逐字段写入的缩进问题
        output_file.write(','.join(output_line) + '\n')

问题2:读取CSV后拆分Centroid列

如果已经生成了带括号的CSV文件,可通过以下步骤拆分Centroid为x、y坐标:

处理代码

import pandas as pd

# 读取CSV文件
df = pd.read_csv('draft_Stelle_measurements.csv')

# 去除Centroid列的首尾括号
df['Centroid'] = df['Centroid'].str.strip('()')

# 拆分x、y坐标并转为浮点型
df[['Centroid_x', 'Centroid_y']] = df['Centroid'].str.split(',', expand=True).astype(float)

# 可选:删除原始Centroid列
df = df.drop('Centroid', axis=1)

更优方案:写入时直接拆分Centroid

如果希望从根源避免拆分操作,可在写入CSV时直接将Centroid拆分为两个字段:

from scipy import ndimage
from skimage import measure

labeled_mask, num_labels = ndimage.label(mask, structure=s)
clusters = measure.regionprops(labeled_mask, image) 
# 修改属性列表,拆分Centroid为两个字段
propList = ['Area', 'MajorAxisLength', 'MinorAxisLength', 'Centroid_x', 'Centroid_y']

with open('draft_Stelle_measurements.csv', 'w') as output_file:
    output_file.write('Label,' + ",".join(propList) + '\n')
    
    for cluster_props in clusters:
        centroid_x, centroid_y = cluster_props['Centroid']
        output_line = [
            str(cluster_props['label']),
            str(cluster_props['Area']),
            str(cluster_props['MajorAxisLength']),
            str(cluster_props['MinorAxisLength']),
            str(centroid_x),
            str(centroid_y)
        ]
        output_file.write(','.join(output_line) + '\n')

内容的提问来源于stack exchange,提问作者Zia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:20:52