4
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

画像中の輝度値の平均・標準偏差を求める

Last updated at Posted at 2020-06-20

目的

画像中の輝度値のヒストグラム、平均・分散を求めた際の備忘録です

コード

以下の画像のヒストグラム、平均・標準偏差を求めます
lena.png : テスト用の画像
black.png : 一様に真っ黒な画像

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)
    # 一次元配列化
    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("---", img_name)
    print("mean    : ", mean)
    print("stddev  : ", std)
    print("median  : ", median)
    print("mode    : ", mode)

print_stat('lena.png')
print_stat('black.png')

結果

$ 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

その他

もう少しコマンドラインから使い易くするなら以下

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)
    # 一次元配列化
    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

参考

Python3 & OpenCV で画像処理を学ぶ[2] 〜 情報可視化のためのヒストグラム基礎実験

4
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?