DOMMETI commited on
Commit
b3a317f
Β·
verified Β·
1 Parent(s): 32e2a77

Update pages/2_Player_Comparison_Throw_Image.py

Browse files
pages/2_Player_Comparison_Throw_Image.py CHANGED
@@ -2,87 +2,55 @@ import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
  import cv2
 
5
  from PIL import Image
6
- import pickle
7
  import plotly.express as px
8
 
9
- # Load Haar Cascade for face detection
10
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
11
-
12
- # Load model
13
  @st.cache_resource
14
  def load_model():
15
- with open("final_model (2).pkl", "rb") as f:
16
- return pickle.load(f)
 
 
 
17
 
18
- # Load player stats data
19
  @st.cache_data
20
  def load_data():
21
  return pd.read_csv("Final_Data.csv")
22
 
23
- # Find the image size (width x height) that gives the expected number of pixels
24
- def get_target_shape(expected_features):
25
- for h in range(100, 200):
26
- for w in range(100, 200):
27
- if h * w == expected_features:
28
- return (w, h) # OpenCV uses (width, height)
29
- return None
30
-
31
- # Predict player name from image
32
- def detect_and_predict_face(image_file, model):
33
- import cv2
34
- import numpy as np
35
- from PIL import Image
36
-
37
- # Load image and convert to grayscale
38
- image = Image.open(image_file).convert("RGB")
39
- img_np = np.array(image)
40
- gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
41
 
42
- # Detect face
 
 
 
43
  faces = face_cascade.detectMultiScale(gray, 1.3, 5)
 
44
  if len(faces) == 0:
45
  return None, "⚠️ No face detected!"
46
 
47
- # Crop face
48
  x, y, w, h = faces[0]
49
  face = gray[y:y+h, x:x+w]
 
 
50
 
51
- # Resize to match training dimensions: 113x109
52
- resized_face = cv2.resize(face, (113, 109)) # width x height = 12289
53
- flattened = resized_face.flatten().reshape(1, -1)
54
-
55
- # Ensure shape matches exactly
56
- expected_features = 12289
57
- if flattened.shape[1] > expected_features:
58
- flattened = flattened[:, :expected_features]
59
- elif flattened.shape[1] < expected_features:
60
- padding = expected_features - flattened.shape[1]
61
- flattened = np.pad(flattened, ((0, 0), (0, padding)), mode='constant')
62
-
63
- # Predict
64
- pred_name = model.predict(flattened)[0]
65
  return pred_name, None
66
 
 
 
 
67
 
68
-
69
-
70
-
71
- # Get player details from the dataset
72
- def get_player_details(df, player_name):
73
- return df[df['Player'] == player_name].iloc[0]
74
-
75
- # Plotting functions
76
  def plot_matches_pie(player_data):
77
  matches_stats = {
78
  'Format': ['Test', 'ODI', 'T20', 'IPL'],
79
  'Matches': [player_data['Matches_Test'], player_data['Matches_ODI'], player_data['Matches_T20'], player_data['Matches_IPL']]
80
  }
81
- df_matches = pd.DataFrame(matches_stats)
82
- fig = px.pie(df_matches, names='Format', values='Matches',
83
- title=f"🏏 {player_data['Player']} - Matches Played 🎯",
84
- hover_data=['Matches'])
85
- fig.update_traces(textinfo='percent+label')
86
  st.plotly_chart(fig)
87
 
88
  def plot_batting_stats(player_data):
@@ -95,10 +63,10 @@ def plot_batting_stats(player_data):
95
  'Strike Rate': [player_data['batting_SR_Test'], player_data['batting_SR_ODI'], player_data['batting_SR_T20'], player_data['batting_SR_IPL']]
96
  }
97
  df = pd.DataFrame(stats)
98
- st.plotly_chart(px.bar(df, x='Format', y='Runs', title=f"πŸƒβ€β™‚οΈ {player_data['Player']} - Runs Scored πŸ’―", color='Format', text='Runs'))
99
- st.plotly_chart(px.bar(df, x='Format', y='Average', title=f"πŸ“Š {player_data['Player']} - Batting Average ⭐", color='Format', text='Average'))
100
- st.plotly_chart(px.bar(df, x='Format', y='Sixes', title=f"πŸ”₯ {player_data['Player']} - Sixes πŸš€", color='Format', text='Sixes'))
101
- st.plotly_chart(px.bar(df, x='Format', y='Fours', title=f"🎯 {player_data['Player']} - Fours ⚑", color='Format', text='Fours'))
102
  st.plotly_chart(px.line(df, x='Format', y='Strike Rate', title=f"⚑ {player_data['Player']} - Strike Rate 🎯", markers=True, text='Strike Rate'))
103
 
104
  def plot_bowling_stats(player_data):
@@ -110,56 +78,53 @@ def plot_bowling_stats(player_data):
110
  'Strike Rate': [player_data['bowling_Test_SR'], player_data['bowling_ODI_SR'], player_data['bowling_T20_SR'], player_data['bowling_IPL_SR']]
111
  }
112
  df = pd.DataFrame(stats)
113
- st.plotly_chart(px.bar(df, x='Format', y='Wickets', title=f"🎳 {player_data['Player']} - Wickets Taken πŸ†", color='Format', text='Wickets'))
114
- st.plotly_chart(px.bar(df, x='Format', y='Average', title=f"πŸ“ˆ {player_data['Player']} - Bowling Average 🌟", color='Format', text='Average'))
115
  st.plotly_chart(px.line(df, x='Format', y='Economy', title=f"πŸ’° {player_data['Player']} - Economy Rate πŸ“‰", markers=True, text='Economy'))
116
  st.plotly_chart(px.line(df, x='Format', y='Strike Rate', title=f"⚑ {player_data['Player']} - Bowling Strike Rate 🎯", markers=True, text='Strike Rate'))
117
 
118
- # MAIN APP
119
  def main():
120
- st.set_page_config(page_title="Player Face Recognition & Stats Comparison", page_icon="πŸ“Έ", layout="wide")
121
  st.title("πŸ“Έ Upload Two Player Images to Compare Stats")
122
 
123
  model = load_model()
 
124
  df = load_data()
125
 
126
- img1 = st.file_uploader("Upload Image for Player 1", type=["jpg", "jpeg", "png"], key="img1")
127
- img2 = st.file_uploader("Upload Image for Player 2", type=["jpg", "jpeg", "png"], key="img2")
 
128
 
129
  if img1 and img2:
130
  with st.spinner("Detecting and predicting players..."):
131
- pred1, error1 = detect_and_predict_face(img1, model)
132
- pred2, error2 = detect_and_predict_face(img2, model)
133
 
134
- if error1:
135
- st.error(f"Player 1: {error1}")
136
- if error2:
137
- st.error(f"Player 2: {error2}")
138
 
139
- if not error1 and not error2:
140
  st.success(f"βœ… Predicted Players: {pred1} vs {pred2}")
141
-
142
  try:
143
- p1_data = get_player_details(df, pred1)
144
- p2_data = get_player_details(df, pred2)
145
 
146
  col1, col2 = st.columns(2)
147
 
148
  with col1:
149
  st.header(f"πŸ“Œ {pred1}")
150
- plot_matches_pie(p1_data)
151
- plot_batting_stats(p1_data)
152
- plot_bowling_stats(p1_data)
153
 
154
  with col2:
155
  st.header(f"πŸ“Œ {pred2}")
156
- plot_matches_pie(p2_data)
157
- plot_batting_stats(p2_data)
158
- plot_bowling_stats(p2_data)
159
 
160
  except Exception as e:
161
- st.error(f"❌ Player stats not found: {e}")
162
 
163
  if __name__ == "__main__":
164
  main()
165
-
 
2
  import pandas as pd
3
  import numpy as np
4
  import cv2
5
+ import joblib
6
  from PIL import Image
 
7
  import plotly.express as px
8
 
9
+ # Load models and data
 
 
 
10
  @st.cache_resource
11
  def load_model():
12
+ return joblib.load("svc_face_classifier(1).pkl")
13
+
14
+ @st.cache_resource
15
+ def load_label_encoder():
16
+ return joblib.load("label_encoder.pkl")
17
 
 
18
  @st.cache_data
19
  def load_data():
20
  return pd.read_csv("Final_Data.csv")
21
 
22
+ # Haar Cascade
23
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # Detect + Predict
26
+ def detect_and_predict_face(image_file, model, label_encoder):
27
+ image = Image.open(image_file).convert("RGB")
28
+ gray = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
29
  faces = face_cascade.detectMultiScale(gray, 1.3, 5)
30
+
31
  if len(faces) == 0:
32
  return None, "⚠️ No face detected!"
33
 
 
34
  x, y, w, h = faces[0]
35
  face = gray[y:y+h, x:x+w]
36
+ resized = cv2.resize(face, (64, 64))
37
+ flattened = resized.flatten().reshape(1, -1)
38
 
39
+ pred_label = model.predict(flattened)[0]
40
+ pred_name = label_encoder.inverse_transform([pred_label])[0]
 
 
 
 
 
 
 
 
 
 
 
 
41
  return pred_name, None
42
 
43
+ # Player stat functions
44
+ def get_player_details(df, name):
45
+ return df[df['Player'] == name].iloc[0]
46
 
 
 
 
 
 
 
 
 
47
  def plot_matches_pie(player_data):
48
  matches_stats = {
49
  'Format': ['Test', 'ODI', 'T20', 'IPL'],
50
  'Matches': [player_data['Matches_Test'], player_data['Matches_ODI'], player_data['Matches_T20'], player_data['Matches_IPL']]
51
  }
52
+ fig = px.pie(pd.DataFrame(matches_stats), names='Format', values='Matches',
53
+ title=f"🏏 {player_data['Player']} - Matches Played 🎯")
 
 
 
54
  st.plotly_chart(fig)
55
 
56
  def plot_batting_stats(player_data):
 
63
  'Strike Rate': [player_data['batting_SR_Test'], player_data['batting_SR_ODI'], player_data['batting_SR_T20'], player_data['batting_SR_IPL']]
64
  }
65
  df = pd.DataFrame(stats)
66
+ st.plotly_chart(px.bar(df, x='Format', y='Runs', title=f"πŸƒβ€β™‚οΈ {player_data['Player']} - Runs Scored πŸ’―", text='Runs'))
67
+ st.plotly_chart(px.bar(df, x='Format', y='Average', title=f"πŸ“Š {player_data['Player']} - Batting Average ⭐", text='Average'))
68
+ st.plotly_chart(px.bar(df, x='Format', y='Sixes', title=f"πŸ”₯ {player_data['Player']} - Sixes πŸš€", text='Sixes'))
69
+ st.plotly_chart(px.bar(df, x='Format', y='Fours', title=f"🎯 {player_data['Player']} - Fours ⚑", text='Fours'))
70
  st.plotly_chart(px.line(df, x='Format', y='Strike Rate', title=f"⚑ {player_data['Player']} - Strike Rate 🎯", markers=True, text='Strike Rate'))
71
 
72
  def plot_bowling_stats(player_data):
 
78
  'Strike Rate': [player_data['bowling_Test_SR'], player_data['bowling_ODI_SR'], player_data['bowling_T20_SR'], player_data['bowling_IPL_SR']]
79
  }
80
  df = pd.DataFrame(stats)
81
+ st.plotly_chart(px.bar(df, x='Format', y='Wickets', title=f"🎳 {player_data['Player']} - Wickets Taken πŸ†", text='Wickets'))
82
+ st.plotly_chart(px.bar(df, x='Format', y='Average', title=f"πŸ“ˆ {player_data['Player']} - Bowling Average 🌟", text='Average'))
83
  st.plotly_chart(px.line(df, x='Format', y='Economy', title=f"πŸ’° {player_data['Player']} - Economy Rate πŸ“‰", markers=True, text='Economy'))
84
  st.plotly_chart(px.line(df, x='Format', y='Strike Rate', title=f"⚑ {player_data['Player']} - Bowling Strike Rate 🎯", markers=True, text='Strike Rate'))
85
 
86
+ # Main Streamlit App
87
  def main():
 
88
  st.title("πŸ“Έ Upload Two Player Images to Compare Stats")
89
 
90
  model = load_model()
91
+ label_encoder = load_label_encoder()
92
  df = load_data()
93
 
94
+ col1, col2 = st.columns(2)
95
+ img1 = col1.file_uploader("Upload Image for Player 1", type=["jpg", "jpeg", "png"], key="img1")
96
+ img2 = col2.file_uploader("Upload Image for Player 2", type=["jpg", "jpeg", "png"], key="img2")
97
 
98
  if img1 and img2:
99
  with st.spinner("Detecting and predicting players..."):
100
+ pred1, err1 = detect_and_predict_face(img1, model, label_encoder)
101
+ pred2, err2 = detect_and_predict_face(img2, model, label_encoder)
102
 
103
+ if err1: st.error(f"Player 1: {err1}")
104
+ if err2: st.error(f"Player 2: {err2}")
 
 
105
 
106
+ if not err1 and not err2:
107
  st.success(f"βœ… Predicted Players: {pred1} vs {pred2}")
 
108
  try:
109
+ p1 = get_player_details(df, pred1)
110
+ p2 = get_player_details(df, pred2)
111
 
112
  col1, col2 = st.columns(2)
113
 
114
  with col1:
115
  st.header(f"πŸ“Œ {pred1}")
116
+ plot_matches_pie(p1)
117
+ plot_batting_stats(p1)
118
+ plot_bowling_stats(p1)
119
 
120
  with col2:
121
  st.header(f"πŸ“Œ {pred2}")
122
+ plot_matches_pie(p2)
123
+ plot_batting_stats(p2)
124
+ plot_bowling_stats(p2)
125
 
126
  except Exception as e:
127
+ st.error(f"⚠️ Player stats not found: {e}")
128
 
129
  if __name__ == "__main__":
130
  main()