Tanusree88 commited on
Commit
c90d799
·
verified ·
1 Parent(s): 9d7dcf7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -0
app.py CHANGED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ from transformers import ViTForImageClassification, ViTImageProcessor
5
+ import nibabel as nib # For loading .nii files
6
+ from PIL import Image # For loading .jpg and .jpeg files
7
+
8
+ # Function to preprocess images based on their file format
9
+ def preprocess_image(image_path):
10
+ ext = os.path.splitext(image_path)[-1].lower() # Get the file extension
11
+
12
+ # Case 1: .nii files (NIfTI format)
13
+ if ext == '.nii' or ext == '.nii.gz':
14
+ # Load the .nii image
15
+ nii_image = nib.load(image_path)
16
+ image_data = nii_image.get_fdata()
17
+
18
+ # Convert to tensor and reshape to [C, H, W] format
19
+ image_tensor = torch.tensor(image_data).float()
20
+
21
+ # Handle cases where the image might have a different shape (e.g., single channel vs multiple channels)
22
+ if len(image_tensor.shape) == 3:
23
+ image_tensor = image_tensor.unsqueeze(0) # Add channel dimension if not present
24
+
25
+ # Case 2: .jpg and .jpeg files (JPEG format)
26
+ elif ext in ['.jpg', '.jpeg']:
27
+ # Load the image using PIL
28
+ img = Image.open(image_path).convert('RGB') # Convert to RGB
29
+ img = img.resize((224, 224)) # Resize to the input size expected by ViT (224x224)
30
+
31
+ # Convert to numpy array and then to tensor
32
+ img_np = np.array(img)
33
+ image_tensor = torch.tensor(img_np).permute(2, 0, 1).float() # Rearrange to [C, H, W]
34
+
35
+ else:
36
+ raise ValueError(f"Unsupported file format: {ext}")
37
+
38
+ # Normalize image tensor (if required)
39
+ image_tensor /= 255.0 # Normalize pixel values to [0, 1]
40
+
41
+ return image_tensor