Heaven’s Light is Our Guide
Rajshahi University of Engineering & Technology
Department of
Electrical & Computer Engineering
Assignment
Detecting the precise boundary of a brain tumor from an MRI scan
Course Code: ECE-4223
Course Title: Digital Image Processing
Submitted to: Submitted by:
Oishi Jyoti Md. Tanjim Jahan
Assistant Professor Roll: 2010007
Dept of ECE, RUET Semester: 4th Year EVEN
Submission Date: 27/04/2026
MRI Tumor Detection Digital Image Processing
1. Problem Statement
Detecting the precise boundary of a brain tumor from an MRI scan is one of the more
demanding tasks in medical image analysis. The difficulty does not come from the tumor
being invisible — it usually shows up as a bright region — but from the fact that the
surrounding image is noisy, the boundary is faint in places, and many other brain structures
appear bright at the same time [1].
Three core challenges that must be addressed:
• Noise Handling — Salt-and-pepper and Gaussian noise produce false bright
spots that can be mistaken for tumor tissue [8]
• Edge Connectivity — The tumor outline is often weak and fragmented, leaving
gaps that a naive detector would miss [4]
• Overlapping Objects — The skull, white matter, ventricles, and blood vessels
all overlap spatially with the tumor region and must be excluded [7]
The objective is to design and implement an automated pipeline that handles all three
challenges and produces a clean, accurate tumor boundary drawn over the original scan.
2. Selection of Approach
Several approaches were evaluated before settling on a method. Table 1 summarises how
three candidate techniques compare across the three challenge areas.
Table 1: Comparison of candidate approaches
Technique Noise Handling Edge Connectivity Overlapping
Objects
Canny Edge Detec- Moderate Poor Poor
tion [4]
Watershed Segmenta- Moderate Moderate Moderate
tion [5]
Morphological Strong Strong Strong
Processing [3]
Morphological image processing [1, 3] was chosen because it is the only approach that
addresses all three challenges directly. Unlike edge detectors that work pixel by pixel,
morphological operations work at the region level — they can open and close shapes,
fill holes, and filter regions by size and position. This makes them far more suited to a
problem where the goal is to isolate one specific region inside a complex image.
2
MRI Tumor Detection Digital Image Processing
3. Justification of the Chosen Approach
3.1 Noise Handling
MRI scans are affected by acquisition noise, magnetic field inhomogeneity, and motion
artefacts, all of which introduce unwanted intensity variations [8, 9]. The pipeline addresses
this at two levels.
At the global level, contrast stretching first redistributes pixel intensities uniformly
across the 0–255 range [1]. Otsu’s method [2] then finds the single threshold t∗ that
maximises the between-class variance:
2
∗ µT ω(t) − µ(t)
t = arg max (1)
t ω(t) 1 − ω(t)
where ω(t) is the cumulative probability of pixels below t and µ(t) is their cumulative
mean [2]. The combined binary image is:
BW = BWglobal ∩ BWadaptive (2)
At the local level, adaptive Gaussian thresholding computes a neighbourhood mean,
handling areas where brightness varies spatially across the scan [10]. Morphological
opening then removes any remaining isolated noise blobs that are too small to be the
tumor.
3.2 Edge Connectivity
Even after thresholding, the binary outline of the tumor contains gaps and weak spots [5].
Three operations rebuild the boundary into a continuous line.
Morphological closing [3] applies dilation followed by erosion with a disk-shaped
structuring element. The dilation expands all white regions, causing nearby gap edges
to overlap and merge; the subsequent erosion restores the original size while keeping the
merged boundary intact.
The Hit-or-Miss transform [1] scans the image for a specific cross pattern:
0 1 0
B = 1 1 1
0 1 0
This step identifies and preserves meaningful structural junctions in the boundary that
closing alone might alter.
Boundary extraction is then performed by subtracting the eroded mask from the
closed binary image [1]:
∂R = R − (R ⊖ B) (3)
where R is the closed binary mask and ⊖ denotes erosion. The result is a precise one-
pixel-wide tumor outline. Region filling [6] seals any remaining internal holes before the
boundary step.
3
MRI Tumor Detection Digital Image Processing
3.3 Overlapping Objects
After thresholding, many bright regions appear in the binary image alongside the tumor
[7]. Connected component analysis [6] assigns a unique label to each separate white region,
treating every candidate individually.
Each candidate is then evaluated against two spatial criteria. First, its centroid (cy , cx )
must fall within the central 40% of the image in both dimensions [7]:
0.3R < cy < 0.7R and 0.3C < cx < 0.7C (4)
Second, its area must lie within a clinically plausible range [1]:
500 < Area < 5000 pixels (5)
Any region that fails either test is discarded. A final binary closing with a radius-3 disk
merges any nearby fragments into one solid mask before the boundary overlay is rendered.
4. Processing Pipeline
Table 2: Step-by-step processing pipeline
Step Operation Role in Pipeline
1 Image Reading Load the JPEG scan and convert to
grayscale
2 Contrast Stretching Stretch intensities to the full 0–255 range
[1]
3 Otsu Thresholding Compute the optimal global binary thresh-
old [2]
4 Adaptive Threshold- Compute local thresholds for spatially
ing varying brightness [10]
5 Morphological Open- Erase noise blobs smaller than the struc-
ing turing element [3]
6 Morphological Clos- Close gaps in the boundary and merge
ing nearby fragments [3]
7 Hit-or-Miss Trans- Detect and preserve specific structural
form edge patterns [1]
8 Boundary Extraction Derive the one-pixel outer edge of the bi-
nary region [1]
9 Region Filling Seal internal holes to produce a solid mask
[6]
10 Component Filtering Label regions and discard non-tumor can-
didates [6, 7]
4
MRI Tumor Detection Digital Image Processing
5. Python Implementation
The pipeline is implemented entirely in Python using OpenCV [11], scikit-image [12], and
NumPy. No proprietary toolboxes or pre-trained models are required.
1 import cv2
2 import numpy as np
3 from skimage import measure , morphology , color
4 import matplotlib . pyplot as plt
5
6 # Step 1: Read MRI image
7 I = cv2 . imread ( ’ y108 . jpg ’)
8 Igray = cv2 . cvtColor (I , cv2 . COLO R_BGR2G RAY )
9
10 # Step 2: C o n t r a s t s t r e t c h i n g
11 Ics = cv2 . normalize ( Igray , None , 0 , 255 , cv2 . NORM_MINMAX )
12
13 # Step 3: T h r e s h o l d i n g ( Otsu + a d a p t i v e )
14 _ , BW_global = cv2 . threshold ( Ics , 0 , 255 ,
15 cv2 . THRESH_BINARY + cv2 . THRESH_OTSU )
16 BW_adapt = cv2 . a d a p t i v e T h r e s h o l d ( Ics , 255 ,
17 cv2 . ADAPTIVE_THRESH_GAUSSIAN_C ,
18 cv2 . THRESH_BINARY , 35 , 2)
19 BW = cv2 . bitwise_and ( BW_global , BW_adapt )
20
21 # Step 4: M o r p h o l o g i c a l noise removal
22 kernel = cv2 . g e t S t r u c t u r i n g E l e m e n t ( cv2 . MORPH_ELLIPSE , (3 ,3) )
23 BW_open = cv2 . morphologyEx ( BW , cv2 . MORPH_OPEN , kernel )
24 BW_close = cv2 . morphologyEx ( BW_open , cv2 . MORPH_CLOSE , kernel )
25
26 # Step 5: Hit - or - Miss
27 hit miss_kernel = np . array ([[0 ,1 ,0] ,
28 [1 ,1 ,1] ,
29 [0 ,1 ,0]] , dtype = np . uint8 )
30 BW_hitmiss = cv2 . morphologyEx ( BW_close ,
31 cv2 . MORPH_HITMISS , hitmis s_kernel )
32
33 # Step 6: B o u n d a r y e x t r a c t i o n
34 eroded = cv2 . erode ( BW_close , kernel )
35 boundary = cv2 . subtract ( BW_close , eroded )
36
37 # Step 7: Region filling
38 filled = morphology . r e m o v e _ s m a l l _ h o l e s (
39 BW_close . astype ( bool ) , area _thresh old =1500)
40
41 # Step 8: C o n n e c t e d c o m p o n e n t e x t r a c t i o n
42 labels = measure . label ( filled , connectivity =2)
43 props = measure . regionprops ( labels )
44
45 tumorMask = np . zeros_like ( filled , dtype = bool )
46 for region in props :
47 cy , cx = region . centroid
48 if 0.3* Igray . shape [0] < cy < 0.7* Igray . shape [0] and \
49 0.3* Igray . shape [1] < cx < 0.7* Igray . shape [1]:
50 if 500 < region . area < 5000:
51 tumorMask [ labels == region . label ] = True
52
53 # Step 9: C o n n e c t i v i t y i n t e r p o l a t i o n
54 tumorMask = morphology . binary _closing (
55 tumorMask , morphology . disk (3) )
56
57 # Step 10: Overlay b o u n d a r y
58 tumorBoundary = morphology . dilation ( tumorMask ) ^ tumorMask
59 overlay = color . gray2rgb ( Igray )
60 overlay [ tumorBoundary ] = [255 , 0 , 0]
61
62 # Display
63 fig , axs = plt . subplots (1 , 3 , figsize =(12 , 4) )
64 axs [0]. imshow ( Igray , cmap = ’ gray ’) ; axs [0]. set_title ( " Original MRI " )
65 axs [1]. imshow ( tumorMask , cmap = ’ gray ’) ; axs [1]. set_title ( " Final Tumor Mask " )
66 axs [2]. imshow ( overlay ) ; axs [2]. set_title ( " Tumor Boundary Overlay " )
5
MRI Tumor Detection Digital Image Processing
67 for ax in axs : ax . axis ( ’ off ’)
68 plt . tight_layout ()
69 plt . show ()
Listing 1: Brain tumor boundary detection — complete Python implementation
6. Experimental Results
The pipeline was run on two clinically representative MRI scans — [Link] and [Link]
— to verify that it generalises across different tumor shapes and sizes.
Case 1 — [Link]
Figure 1 shows the output for the first scan. The tumor appears as a bright ring-shaped
region in the upper-left quadrant of the brain. Despite not being centred in the image,
the centroid filter still captured it, and the red boundary follows the outer edge of the
ring accurately without bleeding into surrounding tissue.
Figure 1: Output for [Link]. From left to right: the original grayscale MRI, the binary
tumor mask, and the final overlay with the detected boundary drawn in red.
Case 2 — [Link]
Figure 2 shows the output for the second scan. Here the tumor is a larger, irregular
mass located more centrally. The binary mask captures the full extent of the region,
including its irregular edges, and the red boundary on the overlay aligns well with the
bright area visible in the original scan.
6
MRI Tumor Detection Digital Image Processing
Figure 2: Output for [Link]. From left to right: the original grayscale MRI, the binary
tumor mask, and the final overlay with the detected boundary drawn in red.
In both cases the skull, ventricles, and white matter structures were correctly excluded
from the final mask, confirming that the spatial and area filters are functioning as intended.
7. Conclusion
This assignment set out to automatically detect the boundary of a brain tumor from a
noisy MRI scan — a problem with three distinct challenges: noise, broken edges, and
overlapping structures. The morphological image processing pipeline addressed each one
in turn. Contrast stretching and dual thresholding cleaned the image; opening and closing
reconnected the fragmented boundary; and connected component filtering discarded
everything that was not the tumor.
The results on both test images show that the approach works reliably across different
tumor morphologies without needing any training data or hand-tuned parameters beyond
the area and centroid thresholds. For a clinical tool, this interpretability and simplicity is
a genuine advantage over black-box deep learning approaches, where understanding why
a boundary was drawn in a particular place is much harder to determine [13].
Future improvements could include replacing the fixed centroid filter with a learning-
based region proposal step, and evaluating the method against ground-truth segmentation
masks using metrics such as the Dice coefficient [14] to quantify accuracy more rigorously.
References
[1] R. C. Gonzalez and R. E. Woods, Digital Image Processing, 4th ed. Pearson, 2018.
[2] N. Otsu, “A threshold selection method from gray-level histograms,” IEEE Transac-
tions on Systems, Man, and Cybernetics, vol. 9, no. 1, pp. 62–66, 1979.
[3] J. Serra, Image Analysis and Mathematical Morphology. Academic Press, London,
1983.
7
MRI Tumor Detection Digital Image Processing
[4] J. Canny, “A computational approach to edge detection,” IEEE Transactions on
Pattern Analysis and Machine Intelligence, vol. 8, no. 6, pp. 679–698, 1986.
[5] L. Vincent and P. Soille, “Watersheds in digital spaces: an efficient algorithm based
on immersion simulations,” IEEE Transactions on Pattern Analysis and Machine
Intelligence, vol. 13, no. 6, pp. 583–598, 1991.
[6] R. M. Haralick and L. G. Shapiro, Computer and Robot Vision, vol. 1. Addison-Wesley,
1992.
[7] B. H. Menze et al., “The multimodal brain tumor image segmentation benchmark
(BRATS),” IEEE Transactions on Medical Imaging, vol. 34, no. 10, pp. 1993–2024,
2015.
[8] D. W. Shattuck, S. R. Sandor-Leahy, K. A. Schaper, D. A. Rottenberg, and R. M.
Leahy, “Magnetic resonance image tissue classification using a partial volume model,”
NeuroImage, vol. 13, no. 5, pp. 856–876, 2001.
[9] J. Sijbers, A. J. den Dekker, P. Scheunders, and D. Van Dyck, “Maximum-likelihood
estimation of Rician distribution parameters,” IEEE Transactions on Medical Imaging,
vol. 17, no. 3, pp. 357–361, 1998.
[10] D. Bradley and G. Roth, “Adaptive thresholding using the integral image,” Journal
of Graphics Tools, vol. 12, no. 2, pp. 13–21, 2007.
[11] G. Bradski, “The OpenCV library,” Dr. Dobb’s Journal of Software Tools, 2000.
[12] S. van der Walt et al., “scikit-image: image processing in Python,” PeerJ, vol. 2,
p. e453, 2014.
[13] G. Litjens et al., “A survey on deep learning in medical image analysis,” Medical
Image Analysis, vol. 42, pp. 60–88, 2017.
[14] L. R. Dice, “Measures of the amount of ecologic association between species,” Ecology,
vol. 26, no. 3, pp. 297–302, 1945.