vishnuamar commited on
Commit
abca75a
·
verified ·
1 Parent(s): 378f2f3

first commit

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ Jaffarbadi_sample.png filter=lfs diff=lfs merge=lfs -text
Bhadawari_sample.jpg ADDED
Gir_sample.jpg ADDED
Jaffarbadi_sample.png ADDED

Git LFS Details

  • SHA256: de7354ba8fd542009298eec936629a189ef1af9c9b823d4a18dc81a5fe6c5e62
  • Pointer size: 132 Bytes
  • Size of remote file: 1.38 MB
README.md ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - cattle-breed-classification
5
+ - buffalo-breed-classification
6
+ - livestock-recognition
7
+ - agriculture
8
+ - computer-vision
9
+ - onnx
10
+ - resnet50
11
+ pipeline_tag: image-classification
12
+ base_model: microsoft/resnet-50
13
+ ---
14
+
15
+ # Cattle & Buffalo Breed Classification Model
16
+
17
+ This model classifies cattle and buffalo breeds using computer vision. It's based on ResNet-50 architecture and trained to recognize 10 different breeds.
18
+
19
+ ## Model Description
20
+
21
+ - **Model Type**: Feature extraction + similarity matching
22
+ - **Architecture**: ResNet-50 backbone with L2 normalization
23
+ - **Format**: ONNX (89.6MB)
24
+ - **Input**: RGB images (224x224)
25
+ - **Output**: 2048-dimensional feature vectors
26
+ - **Classification**: Cosine similarity with breed prototypes
27
+
28
+ ## Supported Breeds
29
+
30
+ ### Buffalo Breeds (5)
31
+ - Bhadawari
32
+ - Jaffarbadi
33
+ - Mehsana
34
+ - Murrah
35
+ - Surti
36
+
37
+ ### Cattle Breeds (5)
38
+ - Gir
39
+ - Kankrej
40
+ - Ongole
41
+ - Sahiwal
42
+ - Tharparkar
43
+
44
+ ## Usage
45
+
46
+ ### Using ONNX Runtime
47
+
48
+ ```python
49
+ import onnxruntime as ort
50
+ import numpy as np
51
+ from PIL import Image
52
+ import json
53
+
54
+ # Load model
55
+ session = ort.InferenceSession('model.onnx')
56
+
57
+ # Load breed prototypes
58
+ with open('prototypes.json', 'r') as f:
59
+ prototypes = json.load(f)
60
+
61
+ # Preprocess image
62
+ def preprocess_image(image_path):
63
+ from torchvision import transforms
64
+
65
+ transform = transforms.Compose([
66
+ transforms.Resize(256),
67
+ transforms.CenterCrop(224),
68
+ transforms.ToTensor(),
69
+ transforms.Normalize(
70
+ mean=[0.485, 0.456, 0.406],
71
+ std=[0.229, 0.224, 0.225]
72
+ )
73
+ ])
74
+
75
+ image = Image.open(image_path).convert('RGB')
76
+ tensor = transform(image).unsqueeze(0)
77
+ return tensor.numpy()
78
+
79
+ # Predict breed
80
+ def predict_breed(image_path):
81
+ # Get features
82
+ input_data = preprocess_image(image_path)
83
+ features = session.run(None, {'input': input_data})[0][0]
84
+
85
+ # Calculate similarities
86
+ similarities = {}
87
+ for breed, prototype in prototypes['prototypes'].items():
88
+ similarity = np.dot(features, prototype)
89
+ similarities[breed] = float(similarity)
90
+
91
+ # Get top prediction
92
+ predicted_breed = max(similarities, key=similarities.get)
93
+ confidence = similarities[predicted_breed]
94
+
95
+ return predicted_breed, confidence, similarities
96
+
97
+ # Example usage
98
+ breed, confidence, all_scores = predict_breed('path/to/image.jpg')
99
+ print(f"Predicted breed: {breed}")
100
+ print(f"Confidence: {confidence:.4f}")
101
+ ```
102
+
103
+ ### Integration with Mobile Apps
104
+
105
+ ```javascript
106
+ // React Native example
107
+ import { ONNX } from 'onnxjs-react-native';
108
+
109
+ const model = new ONNX.InferenceSession();
110
+ await model.loadModel('path/to/model.onnx');
111
+
112
+ const prediction = await model.run([preprocessedImageTensor]);
113
+ // Process with prototypes for final classification
114
+ ```
115
+
116
+ ## Model Performance
117
+
118
+ - **Inference Time**: ~45-50ms (CPU)
119
+ - **Model Size**: 89.6MB
120
+ - **Accuracy**: Optimized for livestock breed recognition
121
+ - **Platforms**: Cross-platform (ONNX Runtime support)
122
+
123
+ ## Files Included
124
+
125
+ - `model.onnx`: The trained ONNX model
126
+ - `prototypes.json`: Breed prototype vectors for classification
127
+ - `config.json`: Model configuration and metadata
128
+ - `sample_images/`: Example images for testing
129
+
130
+ ## Technical Details
131
+
132
+ - **Feature Extraction**: ResNet-50 backbone → 2048-dim features
133
+ - **Normalization**: L2 normalization applied to features
134
+ - **Classification**: Cosine similarity with pre-computed breed prototypes
135
+ - **Preprocessing**: ImageNet-style normalization (mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
136
+
137
+ ## License
138
+
139
+ Apache 2.0
140
+
141
+ ## Citation
142
+
143
+ If you use this model, please cite:
144
+ ```
145
+ @misc{cattle-breed-classifier,
146
+ title={Cattle and Buffalo Breed Classification Model},
147
+ author={Your Name},
148
+ year={2025},
149
+ publisher={Hugging Face},
150
+ url={https://huggingface.co/your-username/cattle-breed-classifier}
151
+ }
152
+ ```
153
+
154
+ ## Contact
155
+
156
+ For questions or issues, please open an issue in the model repository.
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": ["CustomFeatureExtractor"],
3
+ "model_type": "custom",
4
+ "task": "image-classification",
5
+ "framework": "onnx",
6
+ "pipeline_tag": "image-classification",
7
+ "license": "apache-2.0",
8
+ "tags": [
9
+ "cattle-breed-classification",
10
+ "buffalo-breed-classification",
11
+ "livestock-recognition",
12
+ "agriculture",
13
+ "computer-vision",
14
+ "onnx",
15
+ "resnet50"
16
+ ],
17
+ "base_model": "microsoft/resnet-50",
18
+ "num_classes": 10,
19
+ "breeds": [
20
+ "Bhadawari",
21
+ "Gir",
22
+ "Jaffarbadi",
23
+ "Kankrej",
24
+ "Mehsana",
25
+ "Murrah",
26
+ "Ongole",
27
+ "Sahiwal",
28
+ "Surti",
29
+ "Tharparkar"
30
+ ],
31
+ "input_size": [224, 224],
32
+ "feature_dim": 2048,
33
+ "preprocessing": {
34
+ "image_mean": [0.485, 0.456, 0.406],
35
+ "image_std": [0.229, 0.224, 0.225],
36
+ "size": 256,
37
+ "crop_size": 224
38
+ }
39
+ }
example_usage.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Model Hub Integration Example
3
+ ==========================================
4
+
5
+ This script demonstrates how to use the cattle breed classification model
6
+ from Hugging Face Model Hub.
7
+ """
8
+
9
+ import onnxruntime as ort
10
+ import numpy as np
11
+ import json
12
+ from PIL import Image
13
+ from torchvision import transforms
14
+ import requests
15
+ from huggingface_hub import hf_hub_download
16
+ import os
17
+
18
+ class CattleBreedClassifier:
19
+ def __init__(self, model_name="your-username/cattle-breed-classifier"):
20
+ """
21
+ Initialize the classifier by downloading model files from Hugging Face
22
+
23
+ Args:
24
+ model_name: HuggingFace model repository name
25
+ """
26
+ self.model_name = model_name
27
+ self.session = None
28
+ self.prototypes = None
29
+ self.metadata = None
30
+
31
+ # Download and load model files
32
+ self._download_model_files()
33
+ self._load_model()
34
+ self._load_prototypes()
35
+
36
+ def _download_model_files(self):
37
+ """Download model files from Hugging Face Hub"""
38
+ print("📥 Downloading model files from Hugging Face...")
39
+
40
+ # Download ONNX model
41
+ self.model_path = hf_hub_download(
42
+ repo_id=self.model_name,
43
+ filename="model.onnx"
44
+ )
45
+
46
+ # Download prototypes
47
+ self.prototypes_path = hf_hub_download(
48
+ repo_id=self.model_name,
49
+ filename="prototypes.json"
50
+ )
51
+
52
+ # Download metadata
53
+ self.metadata_path = hf_hub_download(
54
+ repo_id=self.model_name,
55
+ filename="metadata.json"
56
+ )
57
+
58
+ print("✅ Model files downloaded successfully!")
59
+
60
+ def _load_model(self):
61
+ """Load the ONNX model"""
62
+ self.session = ort.InferenceSession(self.model_path)
63
+ print("✅ ONNX model loaded")
64
+
65
+ def _load_prototypes(self):
66
+ """Load breed prototypes"""
67
+ with open(self.prototypes_path, 'r') as f:
68
+ self.prototypes = json.load(f)
69
+
70
+ with open(self.metadata_path, 'r') as f:
71
+ self.metadata = json.load(f)
72
+
73
+ print(f"✅ Loaded prototypes for {len(self.prototypes['prototypes'])} breeds")
74
+
75
+ def preprocess_image(self, image_input):
76
+ """
77
+ Preprocess image for model inference
78
+
79
+ Args:
80
+ image_input: PIL Image, numpy array, or file path
81
+
82
+ Returns:
83
+ numpy.ndarray: Preprocessed image tensor
84
+ """
85
+ # Handle different input types
86
+ if isinstance(image_input, str):
87
+ image = Image.open(image_input).convert('RGB')
88
+ elif isinstance(image_input, np.ndarray):
89
+ image = Image.fromarray(image_input).convert('RGB')
90
+ else:
91
+ image = image_input.convert('RGB')
92
+
93
+ # Apply preprocessing
94
+ transform = transforms.Compose([
95
+ transforms.Resize(256),
96
+ transforms.CenterCrop(224),
97
+ transforms.ToTensor(),
98
+ transforms.Normalize(
99
+ mean=[0.485, 0.456, 0.406],
100
+ std=[0.229, 0.224, 0.225]
101
+ )
102
+ ])
103
+
104
+ tensor = transform(image).unsqueeze(0)
105
+ return tensor.numpy()
106
+
107
+ def predict(self, image_input, return_all_scores=False):
108
+ """
109
+ Predict cattle/buffalo breed from image
110
+
111
+ Args:
112
+ image_input: Image input (PIL Image, numpy array, or file path)
113
+ return_all_scores: Whether to return scores for all breeds
114
+
115
+ Returns:
116
+ dict: Prediction results
117
+ """
118
+ # Preprocess image
119
+ input_data = self.preprocess_image(image_input)
120
+
121
+ # Run inference
122
+ features = self.session.run(None, {'input': input_data})[0][0]
123
+
124
+ # Calculate similarities with all breed prototypes
125
+ similarities = {}
126
+ for breed, prototype in self.prototypes['prototypes'].items():
127
+ similarity = np.dot(features, np.array(prototype))
128
+ similarities[breed] = float(similarity)
129
+
130
+ # Get top prediction
131
+ predicted_breed = max(similarities, key=similarities.get)
132
+ confidence = similarities[predicted_breed]
133
+
134
+ # Determine animal type
135
+ buffalo_breeds = ['Bhadawari', 'Jaffarbadi', 'Mehsana', 'Murrah', 'Surti']
136
+ animal_type = 'Buffalo' if predicted_breed in buffalo_breeds else 'Cattle'
137
+
138
+ result = {
139
+ 'predicted_breed': predicted_breed,
140
+ 'confidence': confidence,
141
+ 'animal_type': animal_type
142
+ }
143
+
144
+ if return_all_scores:
145
+ result['all_scores'] = similarities
146
+
147
+ return result
148
+
149
+ # Example usage
150
+ def main():
151
+ # Initialize classifier (will download model from Hugging Face)
152
+ classifier = CattleBreedClassifier("your-username/cattle-breed-classifier")
153
+
154
+ # Example 1: Predict from local image
155
+ image_path = "path/to/your/image.jpg"
156
+ if os.path.exists(image_path):
157
+ result = classifier.predict(image_path, return_all_scores=True)
158
+
159
+ print(f"\n🐄 Prediction Results:")
160
+ print(f"Animal Type: {result['animal_type']}")
161
+ print(f"Predicted Breed: {result['predicted_breed']}")
162
+ print(f"Confidence: {result['confidence']:.4f}")
163
+
164
+ print(f"\n📊 All Breed Scores:")
165
+ for breed, score in sorted(result['all_scores'].items(),
166
+ key=lambda x: x[1], reverse=True):
167
+ print(f" {breed}: {score:.4f}")
168
+
169
+ # Example 2: Predict from PIL Image
170
+ from PIL import Image
171
+ image = Image.open(image_path)
172
+ result = classifier.predict(image)
173
+ print(f"\nDirect PIL prediction: {result['predicted_breed']} ({result['confidence']:.4f})")
174
+
175
+ if __name__ == "__main__":
176
+ main()
metadata.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "resnet50",
3
+ "feature_dim": 2048,
4
+ "input": {
5
+ "size": [3, 224, 224],
6
+ "mean": [0.485, 0.456, 0.406],
7
+ "std": [0.229, 0.224, 0.225]
8
+ },
9
+ "embedding_norm": "l2",
10
+ "similarity": "cosine",
11
+ "optimization_type": "maximum_10breed_near_perfect",
12
+ "breeds": [
13
+ "Bhadawari",
14
+ "Gir",
15
+ "Jaffarbadi",
16
+ "Kankrej",
17
+ "Mehsana",
18
+ "Murrah",
19
+ "Ongole",
20
+ "Sahiwal",
21
+ "Surti",
22
+ "Tharparkar"
23
+ ],
24
+ "buffalo_breeds": ["Bhadawari", "Jaffarbadi", "Mehsana", "Murrah", "Surti"],
25
+ "cattle_breeds": ["Gir", "Kankrej", "Ongole", "Sahiwal", "Tharparkar"],
26
+ "total_breeds": 10,
27
+ "breed_types": {
28
+ "buffalo_count": 5,
29
+ "cattle_count": 5
30
+ }
31
+ }
model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a39d75b315e0abfe9e8ab91c119207f4a649c8d0ddb20d92d5f9b5b77142d3af
3
+ size 93957547
prototypes.json ADDED
The diff for this file is too large to render. See raw diff