改成面向对象
- 源代码
def ret_roi_value_dict(txt_path): output = [] line_number = 0 with open(txt_path, 'r') as file: for line in file: line_number += 1 # 使用正则表达式提取case_name和pixel_value match = re.match(r'Case\s+(.*?)\s+has\s+\[(.*?)\]', line) if match: case_name = match.group(1) pixel_value = list(map(int, match.group(2).split(''))) output.append({'case_name': case_name, 'pixel_value': pixel_value}) else: print(f"Line {line_number} not matched: {line.strip()}") return output def show_roi_value(roi_value_dict, fig_save_path, save_dpi): # 提取所有 "pixel_value" 对应的值 all_pixel_values = [] for item in roi_value_dict: all_pixel_values.extend(item["pixel_value"]) # 计算每个元素的出现次数 unique_elements, counts = np.unique(np.array(all_pixel_values), return_counts=True) # 将 unique_elements 和 counts 转换为 list,并根据 counts 进行排序 sorted_indices = np.argsort(counts)[::-1] sorted_unique_elements = unique_elements[sorted_indices] sorted_counts = counts[sorted_indices] # 定义前五个颜色 top_colors = ['red', 'blue', 'green', 'yellow', 'purple'] bar_colors = ['grey'] * len(unique_elements) # 将排名第二到第六的元素的颜色改为指定颜色 for i in range(1, min(6, len(sorted_unique_elements))): # 找到 sorted_unique_elements[i] 在 original unique_elements 中的位置 original_index = np.where(unique_elements == sorted_unique_elements[i])[0][0] bar_colors[original_index] = top_colors[i-1] # 绘制条形图 plt.figure(figsize=(10, 6)) bars = sns.barplot(x=unique_elements, y=counts, palette=bar_colors) plt.title('TB ROI Information') plt.xlabel('ROI label') plt.ylabel('Case count') plt.xticks(rotation=45) # 旋转 x 轴标签以提高可读性 plt.tight_layout() # 确保标签不会被裁剪 plt.grid(axis="y") # 在每个 bar 上方标注数量 for i, bar in enumerate(bars.patches): height = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2, int(height), f'{int(height)}', ha='center', va='bottom', color='black') # 保存图像 plt.savefig(fig_save_path, dpi=save_dpi) def main(): keyword_list = ["MaXin_50_Newlabel_final", "MaXin_100", "ZhangRui_50_Newlabel_final", "ZhangRui_54"] roi_value_dict = [] for keyword in keyword_list: temp = ret_roi_value_dict(txt_path=f"/homes/xchang/Projects/Multi-center_Tuberculosis/segmentation/nnUNet_dl/{keyword}.txt") roi_value_dict.extend(temp) show_roi_value(roi_value_dict=roi_value_dict, fig_save_path=f"segmentation/nnUNet_dl/roi_new_values_final.png", save_dpi=600)