Views
No views yet
ViT-B/32 pre-trained on ImageNet-21k. It was fine-tuned to classify an STM image as either Artifact-Free or Multi-Tip Artifact.1import torch
2import numpy as np
3from PIL import Image
4from transformers import AutoModelForImageClassification
5
6def preprocess_for_artifact_detection(image_path):
7 """
8 Loads an STM image and converts it to the required 3-channel format
9 (grayscale, magnitude spectrum, phase) for the model.
10 """
11 try:
12 with Image.open(image_path) as img:
13 img = img.convert('L').resize((224, 224))
14 grayscale_img = np.array(img) / 255.0
15 except FileNotFoundError:
16 print(f"Error: The file at {image_path} was not found.")
17 return None
18
19 # Compute FFT, Magnitude, and Phase
20 fft_data = np.fft.fft2(grayscale_img)
21 fft_shifted = np.fft.fftshift(fft_data)
22
23 magnitude_spectrum = np.abs(fft_shifted)
24 phase = np.angle(fft_shifted)
25
26 # Stack channels and convert to PyTorch tensor (C, H, W)
27 stacked_channels = np.stack([grayscale_img, magnitude_spectrum, phase], axis=0)
28
29 # Add a batch dimension (B, C, H, W) and return as float tensor
30 return torch.tensor(stacked_channels, dtype=torch.float32).unsqueeze(0)
31
32# Load the model from the Hub
33model_name = "t0m-R/vit-stm-artifact-fft"
34model = AutoModelForImageClassification.from_pretrained(model_name)
35
36# Preprocess
37image_path = "path/to/your/stm_image" # Replace with your image path
38preprocessed_image = preprocess_for_artifact_detection(image_path)
39
40# Run inference
41with torch.no_grad():
42 logits = model(preprocessed_image).logits
43 predicted_label_id = logits.argmax(-1).item()
44 predicted_label = model.config.id2label[predicted_label_id]
45
46print(f"Predicted Label: {predicted_label}")
47# Expected output: "Predicted Label: Multi-Tip Artifact"1@article{rodani2024enhancing,
2 title={Enhancing Multi-Tip Artifact Detection in STM Images Using Fourier Transform and Vision Transformers},
3 author={Rodani, Tommaso and Ansuini, Alessio and Cazziga, Alberto},
4 journal={Accepted at the 1st Machine Learning for Life and Material Sciences Workshop at ICML},
5 year={2024}
6}