import os import glob #numpy to make arrays in python. import numpy as np #JS ObjectNotation is used to store and transfer the data. import json #Python Image library import PIL.Image as Image #to visualize plots of the training. import matplotlib.pyplot as plt #h5py lets to store huge amount of data and can be retrieved using Numpy. import h5py import scipy.io as io #Import colormap from matplotlib. from matplotlib import cm as CM #scipy for numerical computations. from scipy import spatial import scipy #gaussian filter is used to make the image blur which helps in transition of color in image smoothly. from scipy.ndimage.filters import gaussian_filter #import pytorch as it performs well on images. import torch #taqadam to show the progress of the the training. import tqdm as tqdm # function to create density maps for images def gaussian_filter_density(gt): print (gt.shape) density = np.zeros(gt.shape, dtype=np.float32) gt_count = np.count_nonzero(gt) if gt_count == 0: return density pts = np.array(list(zip(np.nonzero(gt)[1], np.nonzero(gt)[0]))) leafsize = 2048 # build kdtree tree = scipy.spatial.KDTree(pts.copy(), leafsize=leafsize) # query kdtree distances, locations = tree.query(pts, k=4) print ('generate density...') for i, pt in enumerate(pts): pt2d = np.zeros(gt.shape, dtype=np.float32) pt2d[pt[1],pt[0]] = 1. if gt_count > 1: sigma = (distances[i][1]+distances[i][2]+distances[i][3])*0.1 else: sigma = np.average(np.array(gt.shape))/2./2. #case: 1 point density += scipy.ndimage.filters.gaussian_filter(pt2d, sigma, mode='constant') print ('done.') return density root = '/home/sazni/Dataset/ShanghaiTech/ShanghaiTech' part_A_train = os.path.join(root,'part_A/train_data','images') part_A_test = os.path.join(root,'part_A/test_data','images') path_sets = [part_A_train, part_A_test] img_paths = [] for path in path_sets: for img_path in glob.glob(os.path.join(path, '*.jpg')): img_paths.append(img_path) for img_path in img_paths: print (img_path) mat = io.loadmat(img_path.replace('.jpg','.mat').replace('images','ground_truth').replace('IMG_','GT_IMG_')) img= plt.imread(img_path) k = np.zeros((img.shape[0],img.shape[1])) gt = mat["image_info"][0,0][0,0][0] for i in range(0,len(gt)): if int(gt[i][1])<img.shape[0] and int(gt[i][0])<img.shape[1]: k[int(gt[i][1]),int(gt[i][0])]=1 k = gaussian_filter_density(k) with h5py.File(img_path.replace('.jpg','.h5').replace('images','ground_truth'), 'w') as hf: hf['density'] = k # plt.imshow(Image.open(img_paths[0])) # gt_file = h5py.File(img_paths[0].replace('.jpg','.h5').replace('images','ground-truth'),'r') # groundtruth = np.asarray(gt_file['density']) # np.sum(groundtruth)
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |