Skip to content

Instantly share code, notes, and snippets.

@Coderx7
Last active January 12, 2017 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Coderx7/3c4c3346e5e1b0965d618185cfba4960 to your computer and use it in GitHub Desktop.
Save Coderx7/3c4c3346e5e1b0965d618185cfba4960 to your computer and use it in GitHub Desktop.
a non-vectorized and semi-vectorized implementation for calculating std for a batch of images. the semi-vectorized is the one, one should use, since its as fast as the numpy.std
#In the name of God, the most compassionate the most merciful
#a non-vectorized and semi-vectorized implementation for calculating std for a batch of images.
#the semi-vectorized is the one, one should use, since its as fast as the numpy.std
#Seyyed Hossein Hasan pour
#Coderx7@gmail.com
#1/12/2017
import math
#unvectorized version --really slow!
def calc_std_classic(a):
#sum all elements in each channel and divide by the number of elements
batch = a.shape[0]
channel = a.shape[1]
width = a.shape[2]
height = a.shape[3]
#this method is uploaded here : https://gist.github.com/Coderx7/de210643b15e206a4fd6a5da9f7c4d2b
mean = calc_mean_classic2(a)
#https://www.daniweb.com/programming/software-development/threads/348002/mean-and-standard-deviation-of-image
#https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html
sum = np.zeros((channel))
for i in range(batch):
for j in range(channel):
for w in range(width):
for h in range(height):
sum[j] += (abs(a[i,j,w,h] - mean[j])**2)
var = (sum/(width*height*batch))
std = [round(math.sqrt(x),8) for x in var ]
return std
#semi-vectorized, very fast. use this if you face memory shortage errors because of your dataset being too big for your memory
def calc_std_classic2(a):
batch = a.shape[0]
channel = a.shape[1]
width = a.shape[2]
height = a.shape[3]
mean = calc_mean_classic2(a)
sum = np.zeros((channel))
for i in range(batch):
for j in range(channel):
sum[j] += np.sum(abs(a[i,j,:,:] - mean[j])**2)
var = (sum/(width*height*batch))
std = [round(math.sqrt(x),8) for x in var ]
return std
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment