0% found this document useful (0 votes)
10 views17 pages

MRI Tumor Detection with Python Code

The document outlines three different programs for image detection using Python in Google Colab: tumor detection in MRI images using TensorFlow and MobileNetV2, airplane detection using the YOLOv8 model, and face detection using OpenCV. Each program includes steps for installing dependencies, uploading images, processing them, and displaying results. The document also provides code snippets and outputs for each detection task.

Uploaded by

pallavimaurya878
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)
10 views17 pages

MRI Tumor Detection with Python Code

The document outlines three different programs for image detection using Python in Google Colab: tumor detection in MRI images using TensorFlow and MobileNetV2, airplane detection using the YOLOv8 model, and face detection using OpenCV. Each program includes steps for installing dependencies, uploading images, processing them, and displaying results. The document also provides code snippets and outputs for each detection task.

Uploaded by

pallavimaurya878
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

1.

Program of Tumour Detection in Medical image in python via Google Co


lab Compiler

# Step 1: Install dependencies


!pip install tensorflow opencv-python matplotlib

# Step 2: Import necessary libraries


import cv2
import numpy as np
import [Link] as plt
from [Link] import MobileNetV2
from [Link] import Sequential
from [Link] import Dense, GlobalAveragePooling2D
from [Link] import img_to_array, load_img
from [Link] import files

# Step 3: Upload an MRI image


uploaded = [Link]()
image_path = list([Link]())[0]

# Step 4: Display uploaded image


img = [Link](image_path)
img_rgb = [Link](img, cv2.COLOR_BGR2RGB)
[Link](img_rgb)
[Link]("Uploaded MRI Image")
[Link]("off")
[Link]()

# Step 5: Preprocess image


def preprocess_image(image_path, target_size=(224, 224)):
image = load_img(image_path, target_size=target_size)
image = img_to_array(image)
image = image / 255.0 # Normalize
image = np.expand_dims(image, axis=0)
return image

# Step 6: Build a simple model using MobileNetV2


def build_model():
base_model = MobileNetV2(weights='imagenet', include_top=False,
input_shape=(224, 224, 3))
base_model.trainable = False
model = Sequential([
base_model,
GlobalAveragePooling2D(),
Dense(1, activation='sigmoid') # Binary classifier: tumor vs no tumor
])
[Link](optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
return model

model = build_model()

# NOTE: This is a demo. The model isn't trained yet.


# In real use, load trained weights:
# model.load_weights("your_trained_model.h5")

# Step 7: Predict the uploaded image


preprocessed = preprocess_image(image_path)
prediction = [Link](preprocessed)[0][0]

# Step 8: Interpret prediction


label = "Tumor Detected" if prediction > 0.5 else "No Tumor"
color = (0, 0, 255) if prediction > 0.5 else (0, 255, 0)

# Step 9: Display result on image


output_img = [Link]()
[Link](output_img, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
1, color, 2, cv2.LINE_AA)
output_img = [Link](output_img, cv2.COLOR_BGR2RGB)

[Link](output_img)
[Link]("Prediction: " + label)
[Link]("off")
[Link]()

OUTPUT

Requirement already satisfied: tensorflow in /usr/local/lib/python3.11/dist-


packages (2.18.0)
Requirement already satisfied: opencv-python in /usr/local/lib/python3.11/dist-
packages ([Link])
Requirement already satisfied: matplotlib in /usr/local/lib/python3.11/dist-
packages (3.10.0)
Requirement already satisfied: absl-py>=1.0.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (1.4.0)
Requirement already satisfied: astunparse>=1.6.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (1.6.3)
Requirement already satisfied: flatbuffers>=24.3.25 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (25.2.10)
Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (0.6.0)
Requirement already satisfied: google-pasta>=0.1.1 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (0.2.0)
Requirement already satisfied: libclang>=13.0.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (18.1.1)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (3.4.0)
Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages
(from tensorflow) (24.2)
Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!
=4.21.4,!=4.21.5,<6.0.0dev,>=3.20.3 in /usr/local/lib/python3.11/dist-packages
(from tensorflow) (5.29.5)
Requirement already satisfied: requests<3,>=2.21.0 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (2.32.3)
Requirement already satisfied: setuptools in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (75.2.0)
Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (1.17.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (3.1.0)
Requirement already satisfied: typing-extensions>=3.6.6 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (4.14.0)
Requirement already satisfied: wrapt>=1.11.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (1.17.2)
Requirement already satisfied: grpcio<2.0,>=1.24.3 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (1.73.1)
Requirement already satisfied: tensorboard<2.19,>=2.18 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (2.18.0)
Requirement already satisfied: keras>=3.5.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (3.8.0)
Requirement already satisfied: numpy<2.1.0,>=1.26.0 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (2.0.2)
Requirement already satisfied: h5py>=3.11.0 in /usr/local/lib/python3.11/dist-
packages (from tensorflow) (3.14.0)
Requirement already satisfied: ml-dtypes<0.5.0,>=0.4.0 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (0.4.1)
Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in
/usr/local/lib/python3.11/dist-packages (from tensorflow) (0.37.1)
Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.11/dist-
packages (from matplotlib) (1.3.2)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.11/dist-
packages (from matplotlib) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.11/dist-
packages (from matplotlib) (4.58.4)
Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.11/dist-
packages (from matplotlib) (1.4.8)
Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.11/dist-packages
(from matplotlib) (11.2.1)
Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.11/dist-
packages (from matplotlib) (3.2.3)
Requirement already satisfied: python-dateutil>=2.7 in
/usr/local/lib/python3.11/dist-packages (from matplotlib) (2.9.0.post0)
Requirement already satisfied: wheel<1.0,>=0.23.0 in
/usr/local/lib/python3.11/dist-packages (from astunparse>=1.6.0->tensorflow)
(0.45.1)
Requirement already satisfied: rich in /usr/local/lib/python3.11/dist-packages
(from keras>=3.5.0->tensorflow) (13.9.4)
Requirement already satisfied: namex in /usr/local/lib/python3.11/dist-packages
(from keras>=3.5.0->tensorflow) (0.1.0)
Requirement already satisfied: optree in /usr/local/lib/python3.11/dist-packages
(from keras>=3.5.0->tensorflow) (0.16.0)
Requirement already satisfied: charset-normalizer<4,>=2 in
/usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow)
(3.4.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-
packages (from requests<3,>=2.21.0->tensorflow) (3.10)
Requirement already satisfied: urllib3<3,>=1.21.1 in
/usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow)
(2.4.0)
Requirement already satisfied: certifi>=2017.4.17 in
/usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow)
(2025.6.15)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.11/dist-
packages (from tensorboard<2.19,>=2.18->tensorflow) (3.8.2)
Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in
/usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow)
(0.7.2)
Requirement already satisfied: werkzeug>=1.0.1 in /usr/local/lib/python3.11/dist-
packages (from tensorboard<2.19,>=2.18->tensorflow) (3.1.3)
Requirement already satisfied: MarkupSafe>=2.1.1 in /usr/local/lib/python3.11/dist-
packages (from werkzeug>=1.0.1->tensorboard<2.19,>=2.18->tensorflow) (3.0.2)
Requirement already satisfied: markdown-it-py>=2.2.0 in
/usr/local/lib/python3.11/dist-packages (from rich->keras>=3.5.0->tensorflow)
(3.0.0)
Requirement already satisfied: pygments<3.0.0,>=2.13.0 in
/usr/local/lib/python3.11/dist-packages (from rich->keras>=3.5.0->tensorflow)
(2.19.2)
Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-
packages (from markdown-it-py>=2.2.0->rich->keras>=3.5.0->tensorflow) (0.1.2)
Upload widget is only available when the cell has been executed in the current browser session. Please
rerun this cell to enable.
Saving [Link] to [Link]

Downloading data from [Link]


applications/mobilenet_v2/
mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224_no_top.h5
9406464/9406464 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
1/1 ━━━━━━━━━━━━━━━━━━━━ 1s 1s/step
2. Program of Flight detection

2. # ✅ STEP 1: Install dependencies (Ultralytics YOLOv8)

!pip install -q ultralytics


from [Link] import Image, display
from ultralytics import YOLO
import cv2
import [Link] as plt
import os
import torch
from [Link] import files

# ✅ STEP 2: Upload image


uploaded = [Link]()
image_path = next(iter(uploaded)) # get the filename

# ✅ STEP 3: Load YOLOv8 model (pretrained on COCO dataset)


model = YOLO("[Link]") # or '[Link]' for better accuracy

# ✅ STEP 4: Run detection


results = model(image_path)

# ✅ STEP 5: Filter only airplanes (COCO class ID 4)


airplanes = [box for box in results[0].boxes if int([Link][0]) == 4]
num_planes = len(airplanes)

# ✅ STEP 6: Draw bounding boxes


img = [Link](image_path)
for box in airplanes:
x1, y1, x2, y2 = map(int, [Link][0])
[Link](img, (x1, y1), (x2, y2), (0, 255, 0), 2)
[Link](img, "Airplane", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

# ✅ STEP 7: Show result


print(f" Total airplanes detected: {num_planes}")
[Link](figsize=(8, 8))
[Link]([Link](img, cv2.COLOR_BGR2RGB))
[Link]('off')
[Link]()

OUTPUT

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.0/1.0 MB 16.6 MB/s eta 0:00:00


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 363.4/363.4 MB 4.3 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.8/13.8 MB 31.6 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 24.6/24.6 MB 25.9 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 883.7/883.7 kB 52.7 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 664.8/664.8 MB 2.2 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 211.5/211.5 MB 5.3 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 56.3/56.3 MB 17.4 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 127.9/127.9 MB 7.5 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 207.5/207.5 MB 9.9 MB/s eta 0:00:00
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 21.1/21.1 MB 81.3 MB/s eta 0:00:00
Creating new Ultralytics Settings v0.0.6 file ✅
View Ultralytics Settings with 'yolo settings' or at
'/root/.config/Ultralytics/[Link]'
Update Settings with 'yolo settings key=value', i.e. 'yolo settings
runs_dir=path/to/dir'. For help see
[Link]
Upload widget is only available when the cell has been executed in the current browser session. Please
rerun this cell to enable.
Saving [Link] to [Link]
Downloading
[Link] to
'[Link]'...
100%|██████████| 6.25M/6.25M [00:00<00:00, 73.1MB/s]

image 1/1 /content/[Link]: 448x640 12 airplanes, 295.9ms


Speed: 14.8ms preprocess, 295.9ms inference, 46.3ms postprocess per image at shape
(1, 3, 448, 640)
Total airplanes detected: 12
Original image

Detected image

3. Program for face detection


Step 1: Install OpenCV and matplotlib
!pip install opencv-python-headless matplotlib

# Step 2: Import necessary libraries


import cv2
import [Link] as plt
from [Link] import files

# Step 3: Upload an image


uploaded = [Link]()
image_path = list([Link]())[0]

# Step 4: Load Haar cascade face detector


face_cascade = [Link]([Link] +
'haarcascade_frontalface_default.xml')

# Step 5: Read and process the image


img = [Link](image_path)
gray = [Link](img, cv2.COLOR_BGR2GRAY)

# Step 6: Detect faces


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

# Step 7: Draw rectangles around detected faces


for (x, y, w, h) in faces:
[Link](img, (x, y), (x + w, y + h), (0, 255, 0), 2)

# Convert image color for displaying in matplotlib


img_rgb = [Link](img, cv2.COLOR_BGR2RGB)

# Step 8: Display the result


[Link](figsize=(10, 8))
[Link](img_rgb)
[Link]('off')
[Link](f'Detected {len(faces)} face(s)')
[Link]()

OUTPUT

equirement already satisfied: opencv-python-headless in /usr/local/lib/python3.11/dist-packages ([Link])

Requirement already satisfied: matplotlib in /usr/local/lib/python3.11/dist-packages (3.10.0)

Requirement already satisfied: numpy>=1.21.2 in /usr/local/lib/python3.11/dist-packages (from opencv-python-


headless) (2.0.2)
Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib)
(1.3.2)

Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.11/dist-packages (from matplotlib)


(0.12.1)

Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib)


(4.58.4)

Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib)


(1.4.8)

Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib)


(24.2)

Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (11.2.1)

Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib)


(3.2.3)

Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.11/dist-packages (from


matplotlib) (2.9.0.post0)

Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.7-


>matplotlib) (1.17.0)

No file chosen Upload widget is only available when the cell has been executed in the current browser session.
Please rerun this cell to enable.

Saving [Link] to [Link]


Design of Algorithm Example for play in ground or not according to
weather condition in Python

1 Illustrate and demonstrate the working model and principle of Find-S


Aim algorithm
For a given set of training data examples stored in a .CSV file, implement
Program and demonstrate th algorithm to output a description of play schedule
program
Algorithm
1. Initialize h to the most specific hypothesis in H
2. For each positive training instance x
For each attribute constraint ai in h
If the constraint ai is satisfied by x
Then do nothing
Else replace ai in h by the next more general constraint that is satisfied by x
3. Output hypothesis h

To illustrate this algorithm, assume the learner is given the sequence of training examples
from the EnjoySport task

Example Sky AirTemp Humidity Wind Water Forecast EnjoySport


1 Sunny Warm Normal Strong Warm Same Yes
2 Sunny Warm High Strong Warm Same Yes
3 Rainy Cold High Strong Warm Change No
4 Sunny Warm High Strong Cool Change Yes

 The first step of FIND-S is to initialize h to the most specific hypothesis in H


h - (Ø, Ø, Ø, Ø, Ø, Ø)

 Consider the first training example


x1 = <Sunny, Warm, Normal, Strong, Warm, Same>, +
Observing the first training example, it is clear that hypothesis h is too specific. None of
the "Ø" constraints in h are satisfied by this example, so each is replaced by the next
more general constraint that fits the example
h1 = <Sunny, Warm, Normal, Strong, Warm, Same>

 Consider the second training example


x2 = <Sunny, Warm, High, Strong, Warm, Same>, +

The second training example forces the algorithm to further generalize h, this time
substituting a "?" in place of any attribute value in h that is not satisfied by the new
example
h2 = <Sunny, Warm, ?, Strong, Warm, Same>

 Consider the third training example


x3 = <Rainy, Cold, High, Strong, Warm, Change>, -

Upon encountering the third training the algorithm makes no change to h. The FIND-S
algorithm simply ignores every negative example.
h3 = < Sunny, Warm, ?, Strong, Warm, Same>

 Consider the fourth training example


x4 = <Sunny Warm High Strong Cool Change>, +

The fourth example leads to a further generalization of h


h4 = < Sunny, Warm, ?, Strong, ?, ? >

The key property of the FIND-S algorithm


 It is incremental learning i.e., algorithm learns by processing one training example at a
time, updating its hypothesis based on each example
 FIND-S is computationally efficient, especially for small to medium-sized datasets and
can handle noisy data and incomplete training sets
 FIND-S is guaranteed to output the most specific hypothesis within H that is
consistent with the positive training examples
 FIND-S algorithm’s final hypothesis will also be consistent with the negative
examples provided the correct target concept is contained in H, and provided the
training examples are correct.
Training Instances: (The below data is saved as [Link] file)

Sky AirTemp Humidity WindWater Forecast EnjoySport

Sunny Warm Normal StrongWarm Same Yes


Sunny Warm High StrongWarm Same Yes
Rainy Cold High StrongWarm Change No
Sunny Warm High StrongCool Change Yes

Program:

import csv
with open('[Link]', 'r') as file:
data = [row for row in [Link](file)]
print("The total number of training instances are:",len(data)-1,'\n',data[1:])

num_attribute = len(data[0])-1

# Initial hypothesis
hypothesis = ['0']*num_attribute

for i in range(0, len(data)):


if data[i][num_attribute] == 'yes':
for j in range(0, num_attribute):
if hypothesis[j] == '0' or hypothesis[j] == data[i][j]:
hypothesis[j] = data[i][j]
else:
hypothesis[j] = '?'
print("\n The hypothesis for the training instance {} is : \n".format(i),hypothesis)

print("\n The Maximally specific hypothesis for the training instances is ", hypothesis)
Output:

The total number of training instances are: 4


['sunny', 'warm', 'normal', 'strong', 'warm', 'same',
'yes']
['sunny', 'warm', 'high', 'strong', 'warm', 'same', 'yes']
['rainy', 'cold', 'high', 'strong', 'warm', 'change', 'no']
['sunny', 'warm', 'high', 'strong', 'cool', 'change',
'yes']

The hypothesis for the training instance 0


is: ['0', '0', '0', '0', '0', '0']

The hypothesis for the training instance 1 is:


['sunny', 'warm', 'normal', 'strong', 'warm',
'same']

The hypothesis for the training instance 2


is: ['sunny', 'warm', '?', 'strong',
'warm', 'same']

The hypothesis for the training instance 3


is: ['sunny', 'warm', '?', 'strong',
'warm', 'same']

The hypothesis for the training instance 4


is: ['sunny', 'warm', '?', 'strong', '?',
'?']

The Maximally specific hypothesis for the training instance


is
['sunny', 'warm', '?', 'strong', '?', '?']

You might also like