0% found this document useful (0 votes)
5 views19 pages

Medical Image Processing Techniques

The document outlines a series of experiments conducted on medical images using MATLAB and OpenCV, focusing on fundamental operations, image augmentation, enhancement through histogram equalization, preprocessing with discrete wavelet transform, noise removal, gray level transformation, and frequency domain filtering. Each experiment includes code snippets and descriptions of the processes applied to various medical images. The experiments demonstrate techniques such as image rotation, resizing, cropping, color adjustments, and filtering to improve image quality and analysis.

Uploaded by

Gayathri Shiva
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Medical Image Processing Techniques

The document outlines a series of experiments conducted on medical images using MATLAB and OpenCV, focusing on fundamental operations, image augmentation, enhancement through histogram equalization, preprocessing with discrete wavelet transform, noise removal, gray level transformation, and frequency domain filtering. Each experiment includes code snippets and descriptions of the processes applied to various medical images. The experiments demonstrate techniques such as image rotation, resizing, cropping, color adjustments, and filtering to improve image quality and analysis.

Uploaded by

Gayathri Shiva
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EXPERIMENT NO: 1A DATE: 11.07.

2025

REG No: 732922BMR031

FUNDAMENTAL OPERATIONS
MEDICAL IMAGE USING MATLAB

Program:
clc;
clf;
clear all;
a=imread('Z:\22BMR031\Image\xray [Link]');
figure(1),imshow(a),title('Input Original Image 1');
b=rgb2gray(a);
figure(2),imshow(b),title('RGB to GRAY');
c=im2bw(b);
figure(3),imshow(c),title('GRAY TO BINARY');
d=imrotate(a,60);
figure(4),imshow(d),title('ROTATION');
e=imresize(a,0.1);
figure(5),imshow(e),title('RESIZING AN IMAGE');
f=imcrop(a,[75 68 130 112]);
figure(6),imshow(f),title('CROPPING AN IMAGE');
g=imtool(a);
figure(7),imshow(a-50),title('LOW INTENSITY');
figure(8),imshow(a+150),title('HIGH INTENSITY');
EXPERIMENT NO: 1B DATE: 18.07.2025

REGISTER NUMBER: 732922BMR031

FUNDAMENTAL OPERATIONS
MEDICAL IMAGE USING OPEN CV

Program:

import cv2

import numpy as np

image = [Link]('Z:\\22BMR031\\Images\\CT-scan- image [Link]')

[Link]('Original Image', image)

resized = [Link](image, (300, 300))

[Link]('Resized Image', resized)

cropped = image[100:300, 100:300]

[Link]('Cropped Image', cropped)

gray = [Link](image, cv2.COLOR_BGR2GRAY)

[Link]('Grayscale Image', gray)

bright = [Link](image, (50, 50, 50, 0))

[Link]('Brightened Image', bright)

inverted = cv2.bitwise_not(image)

[Link]('Inverted Image', inverted)

[Link](0)

[Link]()
EXPERIMENT NO: 2A DATE: 25.07.2025

REGISTER NUMBER: 732922BMR031

IMAGE AUGMENTATION USING MATLAB

Program:

img = imread('Z:\22BMR031\Images\Xray imahe 1 [Link]');


figure, imshow(img), title('Original Image');
angle = 30;
rotated_img = imrotate(img, angle, 'bilinear', 'crop');
figure, imshow(rotated_img), title(['Rotated Image by ',
num2str(angle), ' degrees']);
flipped_img = flip(img, 2);
figure, imshow(flipped_img), title('Horizontally Flipped
Image');
flipped_v_img = flip(img, 1);
figure, imshow(flipped_v_img), title('Vertically Flipped
Image');
scale_factor = 1.5;
scaled_img = imresize(img, scale_factor);
figure, imshow(scaled_img), title(['Scaled Image (',
num2str(scale_factor*100), '%)']);
hsv_img = rgb2hsv(img);
brightness_jitter = 0.2;
hsv_img(:,:,3) = hsv_img(:,:,3) + brightness_jitter;
hsv_img(:,:,3) = min(hsv_img(:,:,3), 1);
saturation_jitter = 0.3;
hsv_img(:,:,2) = hsv_img(:,:,2) + saturation_jitter;
hsv_img(:,:,2) = min(hsv_img(:,:,2), 1);
color_jittered_img = hsv2rgb(hsv_img);
figure, imshow(color_jittered_img), title('Color Jittered
Image');
noise_var = 0.01;
noisy_img = imnoise(img, 'gaussian', 0, noise_var);
figure, imshow(noisy_img), title('Image with Gaussian Noise');
EXPERIMENT NO: 2B DATE: 25.07.2025

REGISTER NUMBER: 732922BMR031

IMAGE AUGMENTATION USING OPEN CV


Program:
import cv2
import numpy as np
img = [Link](r'Z:\22BMR031\Images\CT-scan image [Link]')
[Link]('Original Image', img)
(h, w) = [Link][:2]
center = (w // 2, h // 2)
angle = 30
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_img = [Link](img, M, (w, h))
[Link](f'Rotated Image by {angle} degrees', rotated_img)
flipped_img = [Link](img, 1)
[Link]('Horizontally Flipped Image', flipped_img)
flipped_v_img = [Link](img, 0)
[Link]('Vertically Flipped Image', flipped_v_img)
scale_factor = 1.5
scaled_img = [Link](img, None, fx=scale_factor, fy=scale_factor)
[Link](f'Scaled Image ({int(scale_factor * 100)}%)', scaled_img)
hsv_img = [Link](img, cv2.COLOR_BGR2HSV).astype(np.float32)
brightness_jitter = 0.2 * 255
saturation_jitter = 0.3 * 255
hsv_img[..., 2] = [Link](hsv_img[..., 2] + brightness_jitter, 0, 255)
hsv_img[..., 1] = [Link](hsv_img[..., 1] + saturation_jitter, 0, 255)
hsv_img = hsv_img.astype(np.uint8)
color_jittered_img = [Link](hsv_img, cv2.COLOR_HSV2BGR)
[Link]('Color Jittered Image', color_jittered_img)
noise_var = 0.01
noise = [Link](0, 255 * noise_var**0.5, [Link]).astype(np.float32)
noisy_img = [Link](np.float32) + noise
noisy_img = [Link](noisy_img, 0, 255).astype(np.uint8)
EXPERIMENT NO: 3A DATE: 01.08.2025

REGISTER NUMBER: 732922BMR031

IMAGE ENHANCEMENT USING HISTOGRAM EQUALIZATION IN MATLAB

Program:

img = imread('Z:\22BMR031\Images\CT-scan- image [Link]');


if size(img, 3) == 3
img = rgb2gray(img);
end

figure;
subplot(2,2,1);
imshow(img);
title('Original Image');

subplot(2,2,2);
imhist(img);
title('Histogram of Original Image');

equalized_img = histeq(img);

subplot(2,2,3);
imshow(equalized_img);
title('Histogram Equalized Image');

subplot(2,2,4);
imhist(equalized_img);
title('Histogram of Equalized Image');
EXPERIMENT NO: 3B DATE: 01.08.2025

REGISTER NUMBER: 732922BMR031

IMAGE ENHANCEMENT USING HISTOGRAM EQUALIZATION IN OPEN CV


Program:

import cv2
import [Link] as plt
# Read grayscale image
img = [Link](r'Z:\22BMR031\Images\MRI_of_Human_Brain image [Link]',
cv2.IMREAD_GRAYSCALE)
if img is None:
print("Error: Image not found or unable to load.")
exit()
# Histogram equalization
equalized_img = [Link](img)
# Plot images and histograms
[Link](figsize=(10,8))
# Original Image
[Link](2,2,1)
[Link](img, cmap='gray')
[Link]('Original Image')
[Link]('off')
# Histogram of Original Image
[Link](2,2,2)
[Link]([Link](), bins=256, range=[0,256])
[Link]('Histogram of Original Image')
[Link]([0, 5000]) # Set y-axis limit here
# Equalized Image
[Link](2,2,3)
[Link](equalized_img, cmap='gray')
[Link]('Equalized Image')
[Link]('off')
# Histogram of Equalized Image
[Link](2,2,4)
[Link](equalized_img.ravel(), bins=256, range=[0,256])
[Link]('Histogram of Equalized Image')
[Link]([0, 5000]) # Set y-axis limit here
plt.tight_layout()[Link]()
EXPERIMENT NO: 4A DATE: 22.08.2025

REGISTER NUMBER: 732922BMR031

PREPROCESSING OF ULTRASOUND IMAGE USING DISCRETE


WAVELET TRANSFORM IN MATLAB

Program:
clc;
clear;
img = imread('Z:\22BMR031\IMAGES\[Link]');
figure, imshow(img), title('Original Image');
if size(img, 3) == 3
img_gray = rgb2gray(img);
else
img_gray = img;
end
figure, imshow(img_gray), title('Grayscale Image');
img_gray = im2double(img_gray);
[LL, LH, HL, HH] = dwt2(img_gray, 'haar');

subplot(2,2,1), imshow(LL,[]), title('Approximation


(LL)');
subplot(2,2,2), imshow(LH,[]), title('Horizontal
Detail (LH)');
subplot(2,2,3), imshow(HL,[]), title('Vertical Detail
(HL)');
subplot(2,2,4), imshow(HH,[]), title('Diagonal Detail
(HH)');
threshold = 0.04;
LH(abs(LH) < threshold) = 0;
HL(abs(HL) < threshold) = 0;
HH(abs(HH) < threshold) = 0;
img_recon = idwt2(LL, LH, HL, HH, 'haar');
figure, imshow(img_recon, []), title('Reconstructed
Image after DWT Preprocessing');
img_enhanced = imadjust(img_recon);
figure, imshow(img_enhanced), title('Contrast
Enhanced Image');
[Link]:4b [Link]:22BMR031
DATE : .08.2025

DWT-BASED ULTRASOUND IMAGE PREPROCESSING USING


OPENCV
import cv2

import numpy as np

import pywt

import [Link] as plt

img = [Link](r'Z:\22BMR031\[Link]', cv2.IMREAD_GRAYSCALE)

img = [Link](np.float64) / 255.0

T = 0.03

wavelets = ['haar', 'db4', 'sym4', 'coif2', 'bior3.5', 'rbio3.3']

results = []

for w in wavelets:

LL, (LH, HL, HH) = pywt.dwt2(img, w)

LH[[Link](LH) < T] = 0

HL[[Link](HL) < T] = 0

HH[[Link](HH) < T] = 0

[Link](pywt.idwt2((LL, (LH, HL, HH)), w))

[Link](figsize=(12, 6))

[Link](2, 4, 1)

[Link](img, cmap='gray')

[Link]('Original')
[Link]('off')

for i, res in enumerate(results):

[Link](2, 4, i + 2)

[Link](res, cmap='gray')

[Link](wavelets[i])

[Link]('off')

plt.tight_layout()

[Link]()
EXPERIMENT NO: 5 DATE: .08.2025

REGISTER NUMBER: 732922BMR031

REMOVAL OF NOISE FOR MEDICAL IMAGES

Program:

import cv2

import numpy as np

import [Link] as plt

from [Link] import denoise_tv_chambolle

# Load image in grayscale

image = [Link]('Z:\\22BMR031\\Images\\[Link]', cv2.IMREAD_GRAYSCALE)

# Add Gaussian noise

def add_noise(img):

noise = [Link](0, 25, [Link])

noisy_img = img + noise

noisy_img = [Link](noisy_img, 0, 255).astype(np.uint8)

return noisy_img

noisy = add_noise(image)

# Apply filters

gaussian = [Link](noisy, (7,7), 0)

median = [Link](noisy, 7)

bilateral = [Link](noisy, 15, 150, 150)

nl_means = [Link](noisy, None, h=20)

tv = denoise_tv_chambolle(noisy / 255.0, weight=0.2, channel_axis=None)


tv = (tv * 255).astype(np.uint8)

# Show images

images = [image, noisy, gaussian, median, bilateral, nl_means, tv]

titles = ['Original', 'Noisy', 'Gaussian', 'Median', 'Bilateral', 'Non-Local Means', 'TV


Denoising']

for i in range(len(images)):

[Link](2, 4, i+1)

[Link](images[i], cmap='gray')

[Link](titles[i])

[Link]('off')

plt.tight_layout()

[Link]()
EXPERIMENT NO: 6 DATE: .08.2025

REGISTER NUMBER: 732922BMR031

GRAY LEVEL TRANSFORMATION IN SPATIAL DOMAIN

Program:

import cv2

import numpy as np

import [Link] as plt

image = [Link]('Z:\\22BMR031\\Images\\XRAY [Link]', cv2.IMREAD_GRAYSCALE)

c = 255 / [Link](1 + [Link](image))

log_transformed = c * [Link](1 + [Link](np.float32))

log_transformed = np.uint8(log_transformed)

gamma = 0.5 # You can try different values: <1 brightens, >1 darkens

gamma_corrected = [Link](255 * (image / 255) ** gamma, dtype='uint8')

min_val = [Link](image)

max_val = [Link](image)

contrast_stretched = ((image - min_val) / (max_val - min_val)) * 255

contrast_stretched = np.uint8(contrast_stretched)

titles = ['Original Image', 'Log Transform', 'Gamma Correction', 'Contrast Stretching']

images = [image, log_transformed, gamma_corrected, contrast_stretched]

[Link](figsize=(12, 8))
for i in range(4):

[Link](2, 2, i + 1)

[Link](images[i], cmap='gray')

[Link](titles[i])

[Link]('off')

plt.tight_layout()

[Link]()
EXPERIMENT NO: 7 DATE: 12.09.2025
REG NO : 732922BMR031
MEDICAL IMAGES ANALYSIS USING FREQUENCY DOMAIN FILTERS
PROGRAM:
import cv2
import numpy as np
import [Link] as plt
img = [Link](r'Z:\22BMR031\xray [Link]', 0)
if img is None:
print("Error: Image not loaded. Check the path.")
exit()
rows, cols = [Link]
dft = [Link](np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = [Link](dft)
def create_mask(shape, t, r1=30, r2=80):
Y, X = [Link][:shape[0], :shape[1]]
c = (shape[0]//2, shape[1]//2)
dist = [Link]((X - c[1])**2 + (Y - c[0])**2)
if t == 'LPF': mask = dist <= r1
elif t == 'HPF': mask = dist >= r1
elif t == 'BPF': mask = (dist >= r1) & (dist <= r2)
elif t == 'BSF': mask = (dist < r1) | (dist > r2)
else: mask = [Link](shape, bool)
return [Link](mask[:, :, None], 2, axis=2).astype(np.float32)
filters = ['LPF', 'HPF', 'BPF', 'BSF']
results = [('Original', img)]
for f in filters:
mask = create_mask((rows, cols), f)
filtered = dft_shift * mask
img_back = [Link]([Link](filtered))
img_back = [Link](img_back[:, :, 0], img_back[:, :, 1])
img_back = [Link](img_back, None, 0, 255,
cv2.NORM_MINMAX).astype(np.uint8)
[Link]((f, img_back))
[Link](figsize=(12, 8))
for i, (title, image) in enumerate(results):
[Link](2, 3, i+1)
[Link](image, cmap='gray')
[Link](title) [Link]('off')
plt.tight_layout() [Link]()
EXPERIMENT NO: 8 DATE: 12.09.2025
REGISTER NUMBER: 732922BMR031
SEGMENT AN IMAGE USING EDGE DETECTION, LINE DETECTION, AND
BOUNDARY DETECTION FOR MEDICAL IMAGES

PROGRAM:
import cv2
import numpy as np
import [Link] as plt
img = [Link](r'Z:\22BMR031\x ray [Link]')
if img is None:
print("Error: Image not loaded. Check file path.")
exit()
gray = [Link](img, cv2.COLOR_BGR2GRAY)
blur = [Link](gray, (5,5), 0)
edges = [Link](blur, 50, 150)
lines = [Link](edges, 1, [Link]/180, 100, minLineLength=50, maxLineGap=10)
line_img = [Link]()
if lines is not None:
for x1,y1,x2,y2 in lines[:,0]:
[Link](line_img, (x1,y1), (x2,y2), (0,255,0), 2)
contours, _ = [Link]([Link](), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
contour_img = [Link]()
[Link](contour_img, contours, -1, (0,0,255), 2)
images = [img, gray, edges, line_img, contour_img]
titles = ['Original', 'Grayscale', 'Edges', 'Lines', 'Contours']
[Link](figsize=(15,8))
for i, (im, title) in enumerate(zip(images, titles), 1):
[Link](2,3,i)
if len([Link]) == 3:
im = [Link](im, cv2.COLOR_BGR2RGB)
[Link](im, cmap='gray' if len([Link])==2 else None)
[Link](title) [Link]('off')
plt.tight_layout() [Link]()
EXPERIMENT NO: 9 DATE: 19.09.2025
REG NO: 732922BMR031
SEGMENT AN IMAGE USING EDGE DETECTION, LINE DETECTION, AND
BOUNDARY DETECTION FOR MEDICAL IMAGES

PROGRAM:
import cv2
import numpy as np
image = [Link]('Z:\\22BMR031\\Images\\.jpg')
original = [Link]()
gray = [Link](image, cv2.COLOR_BGR2GRAY)
blurred = [Link](gray, (5, 5), 0)
edges = [Link](blurred, threshold1=50, threshold2=150)
lines = [Link](edges, rho=1, theta=[Link]/180, threshold=100,
minLineLength=50, maxLineGap=10)
line_image = [Link]()
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
[Link](line_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
contours, _ = [Link]([Link](), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
contour_image = [Link]()
[Link](contour_image, contours, -1, (0, 0, 255), 2)
[Link]("Original Image", original)
[Link]("Grayscale", gray)
[Link]("Edges (Canny)", edges)
[Link]("Lines Detected", line_image)
[Link]("Boundaries (Contours)", contour_image)
[Link](0)
[Link]()
EXPERIMENT NO: 10 DATE: 26.09.2025
REG NO: 732922BMR031

PERFORM THRESHOLDING FREQUENCY OF MEDICAL IMAGE USING


OPTIMAL THRESHOLDING TECHNIQUE

PROGRAM:

import cv2

image = [Link]('Z:\22BMR031\IMAGES\[Link]', 0)

if image is None:

raise ValueError("Image not found or unable to load.


Check the file path.")

retval, thresh_img = [Link](image, 0, 255,


cv2.THRESH_BINARY + cv2.THRESH_OTSU)

print(f"Optimal threshold value by Otsu's method:


{retval}")

[Link]('Original Image', image)

[Link]("Otsu's Thresholding", thresh_img)

[Link](0)

[Link]()
EXPERIMENT NO: 10 DATE: 26.09.2025
REG NO: 732922BMR031

DEVELOP AN ALGORITHM TO EXTRACT THE FEATURES OF MRI IMAGE

PROGRAM:
import cv2
import numpy as np
def preprocess_image(image):
norm_img = [Link](image, None, 0, 255, cv2.NORM_MINMAX)
norm_img = np.uint8(norm_img)
blurred = [Link](norm_img, (5, 5), 0)
return blurred
def extract_intensity_features(roi):
features = {}
features['mean_intensity'] = [Link](roi)
features['std_intensity'] = [Link](roi)
features['max_intensity'] = [Link](roi)
features['min_intensity'] = [Link](roi)
return features
def extract_shape_features(roi_mask):
contours, _ = [Link](roi_mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
if len(contours) == 0:
return {}
cnt = contours[0]
area = [Link](cnt)
perimeter = [Link](cnt, True)
if perimeter == 0:
circularity = 0
else:
circularity = 4 * [Link] * area / (perimeter * perimeter)
x, y, w, h = [Link](cnt)
aspect_ratio = float(w) / h if h != 0 else 0
features = {
'area': area,
'perimeter': perimeter,
'circularity': circularity,
'aspect_ratio': aspect_ratio
}
return features
image = [Link]('Z:\\22BMR025\\Images\\mri-of-the-pelvis image [Link]',
cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError("Image not found or unable to load")
preprocessed_img = preprocess_image(image)
_, roi_mask = [Link](preprocessed_img, 100, 255, cv2.THRESH_BINARY)
roi_pixels = preprocessed_img[roi_mask == 255]
intensity_feats = extract_intensity_features(roi_pixels)
shape_feats = extract_shape_features(roi_mask)
features = {**intensity_feats, **shape_feats}
print("Extracted Features:")
for k, v in [Link]():
print(f"{k}: {v}")

You might also like