Code

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

# Import necessary libraries

import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure, morphology, exposure
from scipy import ndimage

# Install necessary library for file upload in Google Colab


try:
from google.colab import files
except ImportError:
pass

# Function to detect tumor and visualize results


def detect_and_visualize_tumor(image_path):

image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Check if the image was loaded properly


if image is None:
print(f"Error: Unable to load the image {image_path}. Please check the
image path.")
return

print(f"Image {image_path} loaded successfully.")

# Display the original image


plt.figure()
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.show()

# Apply median filter to the original image


image_filtered = cv2.medianBlur(image, 5)

# Display the filtered image


plt.figure()
plt.imshow(image_filtered, cmap='gray')
plt.title('Filtered Image')
plt.axis('off')
plt.show()

# Enhance the filtered image using histogram equalization


image_enhanced = exposure.equalize_hist(image_filtered)

# Apply Gaussian blur to reduce noise


image_blurred = cv2.GaussianBlur(image_enhanced, (5, 5), 0)

# Edge detection using Canny


edges = cv2.Canny((image_blurred * 255).astype(np.uint8), 100, 200)

# Display the enhanced image


plt.figure()
plt.imshow(image_blurred, cmap='gray')
plt.title('Enhanced Image')
plt.axis('off')
plt.show()
# Display edge detection
plt.figure()
plt.imshow(edges, cmap='gray')
plt.title('Edge Detection')
plt.axis('off')
plt.show()

# Tumor detection function using Otsu's thresholding


def detect_tumor(image):
# Apply Otsu's thresholding
_, bw = cv2.threshold((image * 255).astype(np.uint8), 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
label_img = measure.label(bw)
props = measure.regionprops(label_img)

# Consider regions with solidity > 0.7 and significant area


high_dense_area = [prop for prop in props if prop.solidity > 0.7 and
prop.area > 100] # Adding area constraint
if not high_dense_area:
return None, None

max_area = max(high_dense_area, key=lambda x: x.area)


tumor_mask = label_img == max_area.label
tumor_mask = morphology.dilation(tumor_mask, morphology.square(5))

return tumor_mask, max_area.bbox

# Detect the tumor


tumor_mask, bbox = detect_tumor(image_blurred)
if tumor_mask is None:
print("No tumor detected.")
return

# Find contours around the tumor


contours, _ = cv2.findContours((tumor_mask * 255).astype(np.uint8),
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Draw contours on the original image


image_with_contours = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
cv2.drawContours(image_with_contours, contours, -1, (0, 0, 255), 2)

# Display the original image with tumor contours


plt.figure()
plt.imshow(image_with_contours)
plt.title('Detected Tumor with Contours')
plt.axis('off')
plt.show()

# Calculate and display the tumor area


tumor_area = np.sum(tumor_mask)
print(f"Tumor Area (in pixels): {tumor_area}")

# Crop and display the tumor region


min_row, min_col, max_row, max_col = bbox
cropped_tumor = image[min_row:max_row, min_col:max_col]

plt.figure()
plt.imshow(cropped_tumor, cmap='gray')
plt.title('Cropped Tumor Region')
plt.axis('off')
plt.show()

# Zoom into the cropped tumor region


zoom_factor = 2 # Define the zoom factor
zoomed_tumor = cv2.resize(cropped_tumor, None, fx=zoom_factor, fy=zoom_factor,
interpolation=cv2.INTER_LINEAR)

# Display the zoomed tumor image in a separate figure


plt.figure()
plt.imshow(zoomed_tumor, cmap='gray')
plt.title('Zoomed Tumor Region')
plt.axis('off')
plt.show()

# File upload in Google Colab


uploaded = files.upload()

# Process each uploaded image


for image_path in uploaded.keys():
detect_and_visualize_tumor(image_path)

You might also like