It is a memorandum when calculating the histogram of the brightness value in the image and the average / variance.
Find the histogram, mean and standard deviation of the image below lena.png: Test image black.png: Uniformly black image
test.py
import numpy as np
import scipy.stats as sstats
import cv2
def print_stat(fname):
img_name = fname
img = cv2.imread(fname,1)
# Grayscale
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#One-dimensional array
img = np.array(img).flatten()
# img = img[img!=255]
mean = img.mean() #Average value
std = np.std(img) #standard deviation
median = np.median(img) #Median
mode = sstats.mode(img)[0][0] #Mode
print("---", img_name)
print("mean : ", mean)
print("stddev : ", std)
print("median : ", median)
print("mode : ", mode)
print_stat('lena.png')
print_stat('black.png')
result
$ python test.py
--- lena.png
mean : 106.4122314453125
stddev : 45.733566693923045
median : 107.0
mode : 44
--- black.png
mean : 0.0
stddev : 0.0
median : 0.0
mode : 0
If you want to make it a little easier to use from the command line,
test.py
import sys
import numpy as np
import scipy.stats as sstats
import cv2
args = sys.argv
def print_stat(fname):
img_name = fname
img = cv2.imread(fname,1)
# Grayscale
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#One-dimensional array
img = np.array(img).flatten()
# img = img[img!=255]
mean = img.mean()
std = np.std(img)
median = np.median(img)
mode = sstats.mode(img)[0][0]
print("name=" + img_name + ",")
print("mean=" + str(mean) + ",")
print("stddev=" + str(std) + ",")
print("median=" + str(median) + ",")
print("mode=" + str(mode) + ",")
arg1=args[1]
print_stat(arg1)
$ RET=$(python test.py lena.png)
$ echo $RET
name=lena.png , mean=106.4122314453125 , stddev=45.733566693923045 , median=107.0 , mode=44 ,
$ echo $RET | sed -e 's/.*name=//' | cut -d',' -f 1 | awk '{printf "%-20s\n",$1}'
lena.png
$ echo $RET | sed -e 's/.*mean=//' | cut -d',' -f 1 | awk '{printf "%-20s\n",$1}'
106.4122314453125
Recommended Posts