如何在Jupyter中实现Python交互式选择CT图像ROI并自动返回位置
解决Jupyter Notebook中交互式CT图像ROI选择并自动裁剪的方案
直接上可运行的代码,适配Jupyter环境,能自动获取ROI坐标并完成CT数据裁剪,无需手动复制:
from jupyter_dash import JupyterDash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objects as go import numpy as np # 模拟CT数据,替换成你自己的CT数组(维度:[切片数, 高度, 宽度]) newdata = np.random.rand(10, 512, 512) # 取其中一个切片来展示(这里取第5个切片) sample_slice = newdata[4] # 初始化JupyterDash应用 app = JupyterDash(__name__) app.layout = html.Div([ html.H3("CT图像ROI选择与自动裁剪"), # 显示原始CT切片的绘图区域,启用矩形选择工具 dcc.Graph( id='ct-image', figure={ 'data': [go.Heatmap(z=sample_slice, colorscale='gray')], 'layout': go.Layout( dragmode='select', # 启用矩形选择 xaxis={'range': [0, sample_slice.shape[1]]}, yaxis={'range': [0, sample_slice.shape[0]], 'autorange': 'reversed'}, # 反转y轴匹配CT数组的方向 height=600 ) } ), # 显示ROI坐标信息 html.Div(id='roi-coords'), # 显示裁剪后的CT切片 dcc.Graph(id='cropped-ct') ]) @app.callback( [Output('roi-coords', 'children'), Output('cropped-ct', 'figure')], Input('ct-image', 'relayoutData') ) def update_crop(relayout_data): # 初始状态(未选择ROI时) if relayout_data is None: return "未选择ROI", {'data': [], 'layout': go.Layout(title='裁剪结果')} # 提取矩形选择的坐标范围 try: x_min = relayout_data['xaxis.range[0]'] x_max = relayout_data['xaxis.range[1]'] y_min = relayout_data['yaxis.range[0]'] y_max = relayout_data['yaxis.range[1]'] # 转换为数组索引(取整,确保在数组范围内) x1 = max(0, int(np.floor(x_min))) x2 = min(sample_slice.shape[1], int(np.ceil(x_max))) y1 = max(0, int(np.floor(y_min))) y2 = min(sample_slice.shape[0], int(np.ceil(y_max))) # 执行CT数据裁剪(对应你需要的clipw = newdata[:,y1:y2,x1:x2]) clipw = newdata[:, y1:y2, x1:x2] # 取裁剪后的同一切片展示 cropped_slice = clipw[4] # 返回坐标信息和裁剪后的图像 coords_text = f"ROI坐标:x1={x1}, x2={x2}, y1={y1}, y2={y2} | 裁剪后数据维度:{clipw.shape}" cropped_fig = { 'data': [go.Heatmap(z=cropped_slice, colorscale='gray')], 'layout': go.Layout(title='裁剪后的CT切片', height=400) } return coords_text, cropped_fig # 处理未正确获取坐标的情况(比如取消选择) except KeyError: return "ROI选择已取消", {'data': [], 'layout': go.Layout(title='裁剪结果')} # 在Jupyter Notebook中运行应用 app.run_server(mode='inline')
关键说明:
- 环境适配:用
JupyterDash替代普通Dash,直接在Notebook内运行,无需启动外部服务器 - ROI坐标获取:通过
relayoutData自动捕获矩形选择的范围,无需手动复制 - 坐标转换:处理Plotly坐标到数组索引的映射,同时反转y轴,匹配CT数组的存储方向(CT图像的y轴通常是从上到下,而Plotly默认y轴从下到上)
- 自动裁剪:回调函数内直接执行你需要的
clipw = newdata[:,y1:y2,x1:x2],并可直接使用裁剪后的数据进行后续分析
使用方法:
- 替换代码中的
newdata为你的实际CT数组 - 运行代码后,在绘图区域拖动鼠标绘制矩形ROI
- 下方会自动显示ROI坐标和裁剪后的图像,裁剪后的数据
clipw可直接在回调内或扩展代码用于后续步骤
内容的提问来源于stack exchange,提问作者neen
相关产品推荐
相关产品推荐

