It’s a Record-Breaking Crowd! A Must-Read Tutorial to Build your First Crowd Counting Model using Deep Learning

Now, open a new terminal window and type the following commands: cd CSRNet-pytorch python train.

py part_A_train.

json part_A_val.

json 0 0 Again, sit back because this will take some time.

You can reduce the number of epochs in the train.

py file to accelerate the process.

A cool alternate option is to download the pre-trained weights from here if you don’t feel like waiting.

Finally, let’s check our model’s performance on unseen data.

We will use the val.

ipynb file to validate the results.

Remember to change the path to the pretrained weights and images.

#importing libraries import h5py import scipy.

io as io import PIL.

Image as Image import numpy as np import os import glob from matplotlib import pyplot as plt from scipy.

ndimage.

filters import gaussian_filter import scipy import json import torchvision.

transforms.

functional as F from matplotlib import cm as CM from image import * from model import CSRNet import torch %matplotlib inline   #function that we will be using to transform the images from torchvision import datasets, transforms transform=transforms.

Compose([                       transforms.

ToTensor(),transforms.

Normalize(mean=[0.

485, 0.

456, 0.

406],                                     std=[0.

229, 0.

224, 0.

225]),                   ])   #defining the location of dataset root = /home/pulkit/CSRNet/ShanghaiTech/CSRNet-pytorch/ part_A_train = os.

path.

join(root,part_A/train_data,images) part_A_test = os.

path.

join(root,part_A/test_data,images) part_B_train = os.

path.

join(root,part_B/train_data,images) part_B_test = os.

path.

join(root,part_B/test_data,images) path_sets = [part_A_test]   #defining the image path img_paths = [] for path in path_sets:     for img_path in glob.

glob(os.

path.

join(path, *.

jpg)):        img_paths.

append(img_path)   model = CSRNet()   #defining the model model = model.

cuda()   #loading the trained weights checkpoint = torch.

load(part_A/0model_best.

pth.

tar) model.

load_state_dict(checkpoint[state_dict]) Check the MAE (Mean Absolute Error) on test images to evaluate our model: mae = 0 for i in tqdm(range(len(img_paths))):     img = transform(Image.

open(img_paths[i]).

convert(RGB)).

cuda()     gt_file = h5py.

File(img_paths[i].

replace(.

jpg,.

h5).

replace(images,ground-truth),r)     groundtruth = np.

asarray(gt_file[density])     output = model(img.

unsqueeze(0))     mae += abs(output.

detach().

cpu().

sum().

numpy()-np.

sum(groundtruth)) print (mae/len(img_paths)) We got an MAE value of 75.

69 which is pretty good.

Now let’s check the predictions on a single image: from matplotlib import cm as c img = transform(Image.

open(part_A/test_data/images/IMG_100.

jpg).

convert(RGB)).

cuda() output = model(img.

unsqueeze(0)) print(“Predicted Count : “,int(output.

detach().

cpu().

sum().

numpy())) temp = np.

asarray(output.

detach().

cpu().

reshape(output.

detach().

cpu().

shape[2],output.

detach().

cpu().

shape[3])) plt.

imshow(temp,cmap = c.

jet) plt.

show() temp = h5py.

File(part_A/test_data/ground-truth/IMG_100.

h5, r) temp_1 = np.

asarray(temp[density]) plt.

imshow(temp_1,cmap = c.

jet) print(“Original Count : “,int(np.

sum(temp_1)) + 1) plt.

show() print(“Original Image”) plt.

imshow(plt.

imread(part_A/test_data/images/IMG_100.

jpg)) plt.

show() Wow, the original count was 382 and our model estimated there were 384 people in the image.

That is a very impressive performance!.Congratulations on building your own crowd counting model!.  End Notes I encourage you to try out this approach on different images and share your results in the comments section below.

Crowd counting has so many diverse applications and is already seeing adoption by organizations and government bodies.

It is a useful skill to add to your portfolio.

Quite a number of industries will be looking for data scientists who can work with crowd counting algorithms.

Learn it, experiment with it, and give yourself the gift of deep learning!.Did you find this article useful? Feel free to leave your suggestions and feedback for me below, and I’ll be happy to connect with you.

You should also check out the below resources to learn and explore the wonderful world of computer vision: Certified Course: Computer Vision using Deep Learning A Step-by-Step Introduction to the Basic Computer Vision Algorithms Understanding and Building your First Object Detection Model from Scratch Learn Object Detection using the Popular YOLO Framework You can also read this article on Analytics Vidhyas Android APP Share this:Click to share on LinkedIn (Opens in new window)Click to share on Facebook (Opens in new window)Click to share on Twitter (Opens in new window)Click to share on Pocket (Opens in new window)Click to share on Reddit (Opens in new window) Related Articles (adsbygoogle = window.

adsbygoogle || []).

push({});.. More details

Leave a Reply