Fully automated three-dimensional deep learning-based magnetic resonance imaging segmentation of brain cavities in epilepsy surgery.
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 266 lines · 8.9 KB · no license
- from flask import Flask, render_template, request, redirect, url_for
- import os, sys
- sys.path.insert(1, '../scripts')
- from calculate_resected_volumes import calc_resec_vol
- from generate_mask import gen_mask
- from pre2post import pre2post
- from pre2post_deformable import pre2post_deformable
- from register_atlas_to_preop import register_atlas_to_preop
- from jinja2 import Template
- from flask import Markup
- import sqlite3
- import pdfkit
- import time
- import base64
- app = Flask(__name__)
- app.secret_key = b'sdfpow23'
- import tensorflow as tf
- graph = tf.compat.v1.get_default_graph()
- @app.route('/')
- def index():
- return render_template('index.html')
- @app.route('/vol', methods=['GET', 'POST'])
- def vol():
- if request.method == 'POST':
- tic = time.perf_counter()
- # [img, mask, atl, atl_map] = request.files.getlist("file")
- [img, mask] = request.files.getlist("file")
- atlas = request.form['atlas']
- print([img, mask])
- for uploaded_file in [img, mask]:
- if uploaded_file.filename != '':
- uploaded_file.save(os.path.join("static", uploaded_file.filename))
- if atlas == "AAL":
- atlas_nii = "tmp/atlas2post_AAL116_origin_MNI_T1old.nii"
- atlas_txt = "tmp/AAL116.txt"
- df, imgs = calc_resec_vol(
- os.path.join("static", img.filename),
- os.path.join("static", mask.filename),
- # os.path.join("static", atl.filename),
- # os.path.join("static", atl_map.filename),
- atlas_nii,
- atlas_txt,
- os.path.join("static", ""),
- )
- df.sort_values(by="Remaining (%)", inplace=True)
- table_html = df.to_html(
- table_id='report',
- float_format=lambda x: '{0:.2f}'.format(x),
- index=False,
- justify="center"
- )
- toc = time.perf_counter()
- return redirect(url_for('report', vol_table=Markup(table_html), vol_imgs=imgs, post_op_path=img.filename, mask_path=mask.filename))
- return render_template('calculate_vol.html')
- @app.route('/feedback', methods=['GET', 'POST'])
- def feedback():
- if request.method == 'POST':
- try:
- rating = request.form['rating']
- comments = request.form['comments']
- print(rating, comments)
- with sqlite3.connect('database.db') as con:
- cur = con.cursor()
- print('test')
- cur.execute("INSERT INTO feedback (date_time,rating,comments) VALUES (datetime('now'),?,?)",(rating,comments) )
- con.commit()
- msg = "Record successfully added"
- print(msg)
- except Exception as e:
- print(e)
- con.rollback()
- msg = "error in insert operation"
- finally:
- return redirect(url_for("index"))
- con.close()
- @app.route('/report', methods=['GET', 'POST'])
- def report():
- vol_table = request.args.get('vol_table')
- vol_imgs = request.args.get('vol_imgs')
- post_op_path = request.args.get('post_op_path')
- mask_path = request.args.get('mask_path')
- HTML_TEMPLATE = '''
- <!doctype html>
- <html lang="en">
- <head>
- <!-- Required meta tags -->
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- <!-- Bootstrap CSS -->
- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
- <title>DeepResection Report</title>
- </head>
- <body>
- <!-- Viewer -->
- <div class="background-box container">
- <div class="page-header">
- <h1>DeepResection Report</h1>
- </div>
- <div class="row">
- <div class="table table-striped">
- {vol_table}
- </div>
- </div>
- <div class="row">
- <img src="data:image/png;base64, {vol_imgs}"/>
- </div>
- </div>
- </body>
- </html>
- '''
- img = base64.b64encode(open("./static/resection_views.png", "rb").read()).decode()
- options = {'enable-local-file-access': None}
- pdf = pdfkit.from_string(HTML_TEMPLATE.format(vol_table=Markup(vol_table), vol_imgs=str(img)), './static/report.pdf', css='./static/css/style.css', options=options)
- print(os.listdir("tmp"))
- if request.method == 'POST':
- try:
- # rendered_template_enc = rendered_template.encode('utf-8')
- vol_table = request.args.get('vol_table')
- vol_imgs = request.args.get('vol_imgs')
- print("Print Test")
- print("Vol ", vol_table)
- # rendered_html_for_pdf = render_template('report_pdf.html', vol_table=Markup(vol_table), vol_imgs=vol_imgs)
- css = ['./static/css/style.css']
- options = {'enable-local-file-access': None}
- pdf = pdfkit.from_string(HTML_TEMPLATE.format(vol_table=Markup(vol_table), vol_imgs=vol_imgs), 'report.pdf', css=css, options=options)
- return render_template('report.html', vol_table=Markup(vol_table), post_op_path=post_op_path, mask_path=mask_path)
- except Exception as e:
- print(e)
- return render_template('report.html', vol_table=Markup(vol_table), post_op_path=post_op_path, mask_path=mask_path)
- @app.route('/mask', methods=['GET', 'POST'])
- def mask():
- if request.method == 'POST':
- tic = time.perf_counter()
- patient_id = request.form['id']
- atlas = request.form['atlas']
- isContinuous = 'continuous' in request.form
- # postop = request.files['file']
- if len(request.files.getlist("file")) == 2:
- [preop, postop] = request.files.getlist("file")
- elif len(request.files.getlist("file")) == 3:
- [preop, postop, mask] = request.files.getlist("file")
- mask.save(os.path.join("static", mask.filename))
- preop.save(os.path.join("static", preop.filename))
- postop.save(os.path.join("static", postop.filename))
- isDeformable = "deformable" in request.form
- # Deprecated
- # if atlas == "AAL":
- # atlas_nii = "tmp/atlas2post_AAL116_origin_MNI_T1.nii"
- # atlas_txt = "tmp/AAL116.txt"
- if atlas == 'DKT':
- atlas_nii = None
- atlas_txt = "tmp/dkt_atlas_mappings.txt"
- mask_name="{}_predicted_mask.nii.gz".format(patient_id)
- output_dir = "static"
- global graph
- # apply an atlas to pre-operative image, register atlas to post-operative image
- print('pre2post')
- print("deformable? {}".format(isDeformable))
- if isDeformable:
- pre2post_deformable(
- patient_id,
- os.path.join(output_dir, preop.filename),
- os.path.join(output_dir, postop.filename),
- output_dir,
- os.path.join(output_dir, mask.filename)
- )
- else:
- pre2post(
- patient_id,
- os.path.join(output_dir, preop.filename),
- os.path.join(output_dir, postop.filename),
- output_dir
- )
- pre2post_fname = "pre2post_{}".format(preop.filename)
- print("register_atlas_to_preop")
- registered_atlas_fname = register_atlas_to_preop(
- patient_id,
- os.path.join(output_dir, pre2post_fname),
- output_dir
- )
- print("gen_mask")
- with graph.as_default():
- gen_mask(
- os.path.join(output_dir, postop.filename),
- output_dir,
- mask_name,
- isContinuous
- )
- print("calc_resec_volume")
- df, imgs = calc_resec_vol(
- os.path.join(output_dir, postop.filename),
- os.path.join(output_dir, mask_name),
- os.path.join(output_dir, registered_atlas_fname),
- atlas_txt,
- output_dir,
- )
- df.sort_values(by="Remaining (%)", inplace=True)
- table_html = df.to_html(
- table_id='report',
- float_format=lambda x: '{0:.2f}'.format(x),
- index=False,
- justify="center"
- )
- toc = time.perf_counter()
- print("Time elapsed: {:.4f}".format(toc - tic))
- return redirect(url_for('report', vol_table=Markup(table_html), vol_imgs=imgs, post_op_path=postop.filename, mask_path=mask_name))
- return render_template('generate_mask.html')
- @app.route('/about')
- def about():
- return render_template('about.html')
- if __name__ == '__main__':
- app.run(debug=True, threaded=False)
app.py at commit 8fb625d, no license · at the source
Overview
- Neuroimaging Laboratory, Universidade Estadual de Campinas, Campinas, São Paulo, Brazil
- Advanced Imaging and Artificial Intelligence Lab, University of Calgary, Calgary, Alberta, Canada
- School of Medical Sciences, Pontifical Catholic University of Campinas, Campinas, São Paulo, Brazil
- Department of Neurology, Cleveland Clinic Foundation, Cleveland, Ohio, USA
Abstract
Objective: There are several clinical and research applications for determining the amount of brain tissue resected after epilepsy surgery; however, manual segmentation of postoperative magnetic resonance imaging (MRI) is imprecise and time‐consuming. In this study, we developed and benchmarked ResectVol DL, a freely available deep learning‐based tool that performs this task automatically.
Methods: To create ResectVol DL, we trained a UNet‐like deep learning model using postoperative T1‐weighted MRI from epilepsy surgery patients and evaluated it against manual delineations (ground truth). ResectVol DL was also compared with three automated methods (ResectVol 1.1.2, DeepResection, and Auto3DSeg) using Dice similarity coefficient (DSC), Pearson correlation coefficient, and relative volume difference from manual segmentation. To assess false‐positive detections and generalizability beyond epilepsy, we additionally processed images from healthy controls (no resection) and brain tumor cases.
Results: The final epilepsy cohort comprised 120 patients (57 women, mean age at surgery = 31.5 ± 15.9 [SD] years), split into training (n = 72) and test (n = 48) sets. An additional 42 images (22 healthy controls and 20 brain tumor cases) were included to test for false positives and generalizability. Segmentation performance differed across methods (Friedman test, p < .001). ResectVol Dl achieved the highest median DSC (.925), significantly outperforming ResectVol 1.1.2, DeepResection, and Auto3DSeg after Bonferroni correction. Volume‐based metrics were similar for Auto3DSeg and ResectVol DL (r = .988, relative difference = 8.4% vs. r = .985, 8.1%; no significant difference), yet Auto3DSeg produced three false‐positive cavities in no‐surgery controls (3/
Significance: ResectVol DL provides accurate, fully automated segmentation of postoperative resection cavities, offering a robust and reproducible methodological tool for large‐scale postoperative imaging studies in epilepsy surgery. ResectVol DL also provides volumetric information derived from region labeling, which may serve as potential input for predictive models associated with surgery outcome; however, this application has not yet been validated.
Reproduced under the paper's license (CC BY), from the paper cited above.
Repositories
Its files are read in the Code ↔ Paper reader above.
penn-cnt/DeepResection
8fb625dbc3e1e89c7cc4306b02a7c9b0ba3e2885, 25 August 2022Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
27 files
- flask/
app.py , Python, 266 lines - flask/
manage_db.py , Python, 20 lines - flask/
static/ , JavaScript, not shown here._papaya.js - flask/
static/ , JavaScript, 394 linespapaya.js - flask/
templates/ , JavaScript, 394 linespapaya.js - pipeline/
resection_deformable_pip , Shell, 39 lineseline.sh - pipeline/
resection_pipeline.sh , Shell, 40 lines - pipeline/
resection_segmentation_o , Shell, 22 linesnly_pipeline.sh - scripts/
brain_viewer.py , Python, 3 lines - scripts/
calculate_resected_volum , Python, 163 lineses.py - scripts/
data_colab_format.m , MATLAB, 22 lines - scripts/
generate_masks.py , Python, 169 lines - scripts/
generate_png_RE37.m , MATLAB, 30 lines - scripts/
img_square_pad.m , MATLAB, 28 lines - scripts/
majority_vote.py , Python, 66 lines - scripts/
nii2png.m , MATLAB, 29 lines - scripts/
nii2png.py , Python, 47 lines - scripts/
png2nii.m , MATLAB, 94 lines - scripts/
png2nii.py , Python, 78 lines - scripts/
pre2post.py , Python, 37 lines - scripts/
pre2post_deformable.py , Python, 44 lines - scripts/
register_atlas_to_preop. , Python, 30 linespy - scripts/
report_pdf.py , Python, 26 lines - scripts/
subject2colab.m , MATLAB, 54 lines - scripts/
train_GPU.py , Python, 163 lines - scripts/
vol_report.py , Python, 26 lines - README.md, Text, 101 lines
rfcasseb/resectvol_dl
550249a28dee9251d3f21119bfebb80410aa63eb, 22 February 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
7 files
- resectvol_dl.sh, Shell, 325 lines
- rvdl_labeling.sh, Shell, 225 lines
- rvdl_labeling_descrip.py
, Python, 246 lines - rvdl_replace_header.py, Python, 112 lines
- rvdl_tissue_seg.py, Python, 54 lines
- LICENSE, License, 28 lines
- README.md, Text, 177 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 31 scripts, each with its path and the digest of its content;
- no match between paragraphs and code yet;
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data availability statement
The data supporting the findings of this study can be made available upon approval from the ethics committee and through a formal data‐sharing agreement. ResectVol DL is available at github.com/
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 2, 28 September 2026
- Publisher: n/a → Wiley
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 13 authors, 5 keywords, 12 MeSH terms, 4 funders, 24 references.
Cite
This paper
Casseb, R. F., de Campos, B. M., Loos, W. S., Barbosa, M. E. R., Alvim, M. K. M., Paulino, G. C. L., Ghizoni, E., Pucci, F., Worrell, S., Yassuda, C. L., de Souza, R. M., Jehi, L., & Cendes, F. (2026). Fully automated three-dimensional deep learning-based magnetic resonance imaging segmentation of brain cavities in epilepsy surgery. Epilepsia, 67(8), 4207-4218. https://
BibTeX
@article{casseb2026fully
author = {Casseb, Raphael Fernandes and de Campos, Brunno Machado and Loos, Wallace Souza and Barbosa, Marcelo Eduardo Ramos and Alvim, Marina Koutsodontis Machado and Paulino, Gabriel Chagas Lutfala and Ghizoni, Enrico and Pucci, Francesco and Worrell, Samuel and Yassuda, Clarissa Lin and de Souza, Roberto Medeiros and Jehi, Lara and Cendes, Fernando},
title = {{Fully automated three-dimensional deep learning-based magnetic resonance imaging segmentation of brain cavities in epilepsy surgery}},
journal = {Epilepsia},
year = {2026},
month = jun,
volume = {67},
number = {8},
pages = {4207--4218},
publisher = {Wiley},
issn = {0013-9580},
doi = {10.1002/
url = {https://
pmid = {42284022},
pmcid = {PMC13525573}
}
RIS
TY - JOUR
AU - Casseb, Raphael Fernandes
AU - de Campos, Brunno Machado
AU - Loos, Wallace Souza
AU - Barbosa, Marcelo Eduardo Ramos
AU - Alvim, Marina Koutsodontis Machado
AU - Paulino, Gabriel Chagas Lutfala
AU - Ghizoni, Enrico
AU - Pucci, Francesco
AU - Worrell, Samuel
AU - Yassuda, Clarissa Lin
AU - de Souza, Roberto Medeiros
AU - Jehi, Lara
AU - Cendes, Fernando
TI - Fully automated three-dimensional deep learning-based magnetic resonance imaging segmentation of brain cavities in epilepsy surgery
T2 - Epilepsia
J2 - Epilepsia
PY - 2026
DA - 2026/
VL - 67
IS - 8
SP - 4207
EP - 4218
SN - 0013-9580
PB - Wiley
DO - 10.1002/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1002/
"type": "article-journal",
"title": "Fully automated three-dimensional deep learning-based magnetic resonance imaging segmentation of brain cavities in epilepsy surgery",
"container-title": "Epilepsia",
"author": [
{
"family": "Casseb",
"given": "Raphael Fernandes"
},
{
"family": "de Campos",
"given": "Brunno Machado"
},
{
"family": "Loos",
"given": "Wallace Souza"
},
{
"family": "Barbosa",
"given": "Marcelo Eduardo Ramos"
},
{
"family": "Alvim",
"given": "Marina Koutsodontis Machado"
},
{
"family": "Paulino",
"given": "Gabriel Chagas Lutfala"
},
{
"family": "Ghizoni",
"given": "Enrico"
},
{
"family": "Pucci",
"given": "Francesco"
},
{
"family": "Worrell",
"given": "Samuel"
},
{
"family": "Yassuda",
"given": "Clarissa Lin"
},
{
"family": "de Souza",
"given": "Roberto Medeiros"
},
{
"family": "Jehi",
"given": "Lara"
},
{
"family": "Cendes",
"given": "Fernando"
}
],
"container-title-short":
"volume": "67",
"issue": "8",
"page": "4207-4218",
"DOI": "10.1002/
"PMID": "42284022",
"PMCID": "PMC13525573",
"ISSN": "0013-9580",
"publisher": "Wiley",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
12
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1186/s12880-026-02481-2 [code]
- Deep learning-based neuroanatomical profiling reveals population-specific brain changes in multiple sclerosis: a large-scale Middle Eastern study.Journal: BMC medical imagingIn common: imageio, Keras, TensorFlow, 10 other tools, structural MRI / diffusion, clinical / translational, 1 reference
- [2] doi:10.1038/s41586-026-10631-3 [code]
- A prognostic human brain network for diffuse midline glioma.Journal: NatureIn common: Keras, ANTs, TensorFlow, 10 other tools, clinical / translational, 1 reference
- [3] doi:10.1038/s41597-026-07248-6 [code]
- A large-scale fMRI dataset for vision-language semantic association.Journal: Scientific dataIn common: imageio, ANTs, FSL, 10 other tools, 1 reference
- [4] doi:10.1038/s41467-026-71568-9 [code]
- Convergent and selective representations of pain, appetitive processes, aversive processes, and cognitive control in the insula.Journal: Nature communicationsIn common: Nipype, ANTs, FSL, 10 other tools
- [5] doi:10.1038/s41467-026-71151-2 [code]
- Common and distinct neural correlates of social interaction processing and theory of mind in narratives.Journal: Nature communicationsIn common: Nipype, ANTs, FSL, 10 other tools
- [6] doi:10.2463/mrms.mp.2024-0149 [code]
- Image Distortion Correction for Diffusion MR Imaging Using a Transformer-based U-Net.Journal: Magnetic resonance in medical sciences : MRMS : an official journal of Japan Society of Magnetic Resonance in MedicineIn common: nnU-Net, ANTs, FSL, 9 other tools, structural MRI / diffusion, clinical / translational
- [7] doi:10.1002/alz.71649 [code]
- Postmortem brain MRI reveals differential associations of subcortical and limbic volumes with cortical thinning and neurodegenerative pathologies.Journal: Alzheimer's & dementia : the journal of the Alzheimer's AssociationIn common: nnU-Net, ANTs, FSL, 9 other tools, structural MRI / diffusion
- [8] doi:10.7554/elife.107933 [code]
- Modality-agnostic decoding of vision and language from fMRI.Journal: eLifeIn common: Nipype, Nilearn, SPM, 9 other tools, 1 reference
- [9] doi:10.3389/fnins.2026.1870124 [code]
- An end-to-end pipeline for automated fetal brain segmentation and biometry from 3D SSFP MRI.Journal: Frontiers in neuroscienceIn common: nnU-Net, imageio, FSL, 8 other tools, structural MRI / diffusion, 1 reference
- [10] doi:10.1038/s41398-026-04025-2 [code]
- Brain energetic landscapes shape state dysregulation in major depressive disorder: a morphological network controllability perspective.Journal: Translational psychiatryIn common: Nipype, ANTs, FSL, 9 other tools
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 2 repositories of the authors' code, each at its verified commit and with its license, 31 scripts, and 0 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:ac133e100280226a…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
