import gradio as gr import torch import torch.nn as nn import torchvision.models as models import cv2 import numpy as np from PIL import Image from huggingface_hub import hf_hub_download import matplotlib.pyplot as plt from io import BytesIO # ---------- Model Architecture ---------- class Counter(nn.Module): def __init__(self): super().__init__() vgg = models.vgg16_bn(weights=None) self.encoder = nn.Sequential(*list(vgg.features.children())[:33]) self.decoder = nn.Sequential( nn.Conv2d(512, 256, 3, padding=1), nn.ReLU(), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True), nn.Conv2d(256, 128, 3, padding=1), nn.ReLU(), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True), nn.Conv2d(128, 64, 3, padding=1), nn.ReLU(), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True), nn.Conv2d(64, 1, 1) ) def forward(self, x): return self.decoder(self.encoder(x)) # ---------- Download & Load Model ---------- model_path = hf_hub_download( repo_id="malikhannan111/crowd_counter", filename="crowd_counter.pth" ) device = torch.device("cpu") model = Counter().to(device) model.load_state_dict(torch.load(model_path, map_location="cpu")) model.eval() # ---------- Detection Function ---------- def count_crowd(image): img = np.array(image) if len(img.shape) == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) elif img.shape[2] == 4: img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB) img_resized = cv2.resize(img, (512, 384)) img_tensor = torch.tensor( img_resized.transpose(2, 0, 1).astype(np.float32) / 255.0 ).unsqueeze(0).to(device) with torch.no_grad(): pred = model(img_tensor) count = pred.sum().item() # Heatmap generate heatmap = pred.cpu().squeeze().numpy() heatmap = (heatmap - heatmap.min()) / (heatmap.max() - heatmap.min() + 1e-8) # Overlay heatmap on image fig, ax = plt.subplots(figsize=(8, 6)) ax.imshow(img_resized) ax.imshow(heatmap, cmap='jet', alpha=0.5) ax.set_title(f"Crowd Count: {count:.0f} people", fontsize=14, fontweight='bold') ax.axis('off') plt.tight_layout() # Convert to PIL Image buf = BytesIO() plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0) plt.close(fig) buf.seek(0) heatmap_img = Image.open(buf) return f"Crowd Count: {count:.0f} people", heatmap_img # ---------- Gradio UI ---------- with gr.Blocks(title="Crowd Counter") as app: gr.Markdown(""" # 👥 Crowd Counter with Heatmap ### Upload an image to count number of people """) with gr.Row(): image_input = gr.Image(type="pil", label="Upload Image") detect_btn = gr.Button("Count Crowd", variant="primary", size="lg") with gr.Row(): output_text = gr.Textbox(label="Count Result") output_heatmap = gr.Image(type="pil", label="Density Heatmap") detect_btn.click( fn=count_crowd, inputs=image_input, outputs=[output_text, output_heatmap] ) app.launch()