Views
No views yet
google/vit-base-patch16-224pip install torch transformers pillow numpy1import torch
2from PIL import Image
3from transformers import ViTImageProcessor
4import requests
5from io import BytesIO
6
7# Download model files
8model_id = "Rithankoushik/Finetuned_VITmodel"
9device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
11# Load the model and processor
12model = torch.load(
13 hf_hub_download(repo_id=model_id, filename="best_model.pt"),
14 map_location=device
15)
16processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
17
18# Load dataset statistics for denormalization
19import json
20stats = torch.load(
21 hf_hub_download(repo_id=model_id, filename="best_model.pt"),
22 map_location=device
23)
24dataset_stats = stats['dataset_stats']
25
26# Load and process image
27image = Image.open("path_to_image.jpg").convert('RGB')
28inputs = processor(images=image, return_tensors="pt").to(device)
29
30# Inference
31model.eval()
32with torch.no_grad():
33 outputs = model(inputs['pixel_values'])
34
35 # Extract predictions
36 height_normalized = outputs['height'].item()
37 weight_normalized = outputs['weight'].item()
38
39 # Denormalize predictions
40 height_cm = height_normalized * dataset_stats['height_std'] + dataset_stats['height_mean']
41 weight_kg = weight_normalized * dataset_stats['weight_std'] + dataset_stats['weight_mean']
42
43print(f"Predicted Height: {height_cm:.1f} cm ({height_cm/2.54:.1f} inches)")
44print(f"Predicted Weight: {weight_kg:.1f} kg ({weight_kg*2.205:.1f} lbs)")1from huggingface_hub import hf_hub_download
2import torch
3from PIL import Image
4from transformers import ViTImageProcessor
5
6def predict_height_weight(image_path: str) -> dict:
7 """
8 Predict height and weight from an image using the Finetuned ViT model.
9
10 Args:
11 image_path: Path to the image file or URL
12
13 Returns:
14 Dictionary with predicted height (cm) and weight (kg)
15 """
16 model_id = "Rithankoushik/Finetuned_VITmodel"
17 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
19 # Download and load model
20 model_path = hf_hub_download(repo_id=model_id, filename="best_model.pt")
21 checkpoint = torch.load(model_path, map_location=device)
22
23 # Initialize model architecture
24 from transformers import ViTForImageClassification, ViTConfig
25 config = ViTConfig.from_pretrained("google/vit-base-patch16-224")
26
27 # Load model state
28 model_state = checkpoint['model_state_dict']
29 dataset_stats = checkpoint['dataset_stats']
30 model_name = checkpoint['model_name']
31
32 # Create model (you may need to use the custom model class)
33 model = torch.load(model_path, map_location=device)
34 model.to(device)
35 model.eval()
36
37 # Load processor
38 processor = ViTImageProcessor.from_pretrained(model_name)
39
40 # Load image
41 if isinstance(image_path, str) and image_path.startswith(('http://', 'https://')):
42 from PIL import Image
43 import requests
44 response = requests.get(image_path)
45 image = Image.open(BytesIO(response.content)).convert('RGB')
46 else:
47 image = Image.open(image_path).convert('RGB')
48
49 # Preprocess
50 inputs = processor(images=image, return_tensors="pt").to(device)
51
52 # Predict
53 with torch.no_grad():
54 outputs = model(inputs['pixel_values'])
55 height_norm = outputs['height'].item()
56 weight_norm = outputs['weight'].item()
57
58 # Denormalize
59 height_cm = height_norm * dataset_stats['height_std'] + dataset_stats['height_mean']
60 weight_kg = weight_norm * dataset_stats['weight_std'] + dataset_stats['weight_mean']
61
62 return {
63 'height_cm': round(height_cm, 2),
64 'height_inches': round(height_cm / 2.54, 2),
65 'weight_kg': round(weight_kg, 2),
66 'weight_lbs': round(weight_kg * 2.205, 2),
67 'model_id': model_id
68 }
69
70# Example usage
71result = predict_height_weight("path_to_your_image.jpg")
72print(f"Height: {result['height_cm']} cm ({result['height_inches']} inches)")
73print(f"Weight: {result['weight_kg']} kg ({result['weight_lbs']} lbs)")1import torch
2from PIL import Image
3from transformers import ViTImageProcessor
4from huggingface_hub import hf_hub_download
5import os
6
7def batch_predict(image_folder: str) -> list:
8 """Process multiple images at once."""
9
10 model_id = "Rithankoushik/Finetuned_VITmodel"
11 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
13 # Load model and processor
14 model = torch.load(
15 hf_hub_download(repo_id=model_id, filename="best_model.pt"),
16 map_location=device
17 )
18 processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
19 model.eval()
20
21 results = []
22
23 # Get all image files
24 image_files = [f for f in os.listdir(image_folder)
25 if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
26
27 for img_file in image_files:
28 image_path = os.path.join(image_folder, img_file)
29
30 try:
31 image = Image.open(image_path).convert('RGB')
32 inputs = processor(images=image, return_tensors="pt").to(device)
33
34 with torch.no_grad():
35 outputs = model(inputs['pixel_values'])
36 height = outputs['height'].item()
37 weight = outputs['weight'].item()
38
39 results.append({
40 'image': img_file,
41 'height_cm': round(height, 2),
42 'weight_kg': round(weight, 2)
43 })
44 except Exception as e:
45 print(f"Error processing {img_file}: {e}")
46
47 return results
48
49# Process all images in a folder
50predictions = batch_predict("path_to_image_folder")
51for pred in predictions:
52 print(f"{pred['image']}: {pred['height_cm']} cm, {pred['weight_kg']} kg")1height_cm = height_normalized * height_std + height_mean
2weight_kg = weight_normalized * weight_std + weight_meandataset_stats:height_mean: Mean height in datasetheight_std: Standard deviation of heightweight_mean: Mean weight in datasetweight_std: Standard deviation of weight1@model{finetuned_vit_height_weight,
2 title={Finetuned Vision Transformer for Height and Weight Prediction},
3 author={Your Name},
4 year={2024},
5 publisher={Hugging Face},
6 howpublished={\url{https://huggingface.co/Rithankoushik/Finetuned_VITmodel}}
7}