基礎ユニット2(イメージメディア) 第12回(2020/12/24)
関連サイトと資料
サンプル画像
croatia.png
airfield.png
alps.png
ireland.png
imgA.png
imgB.png
imgC.png
サンプルプログラム
histogram1.py
import cv2
# パラメータ
target = 'croatia.png'
# ヒストグラムの算出
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
# 表示
print('ピクセル値 -> 頻度')
sum = 0
for i in range(256):
print('{0} -> {1}'.format(i, int(hist[i][0])))
sum += int(hist[i][0])
total = width * height
print('全ピクセル数: {0}'.format(total))
print('頻度の総和: {0}'.format(sum))
histogram2.py
import cv2
# パラメータ
target = 'croatia.png'
# ヒストグラムの算出
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
hist = cv2.calcHist([img], [0], None, [64], [0, 256])
# 表示
print('ピクセル値(下限,上限) -> 頻度')
sum = 0
for i in range(64):
print('({0},{1}) -> {2}'.format(i*4, (i+1)*4 - 1, int(hist[i][0])))
sum += int(hist[i][0])
total = width * height
print('全ピクセル数: {0}'.format(total))
print('頻度の総和: {0}'.format(sum))
histogram3.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# パラメータ
target = 'croatia.png'
# ヒストグラムの算出
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
# 表示
fp = FontProperties(fname=r'C:\\WINDOWS\\Fonts\\msgothic.ttc', size=12)
val_x = []
val_y = []
for i in range(256):
val_x.append(i)
val_y.append(int(hist[i][0]))
plt.bar(np.array(val_x), np.array(val_y), color="#FF0000")
plt.title('ヒストグラム({0})'.format(target), fontproperties=fp)
plt.xlabel('ピクセル値', fontproperties=fp)
plt.ylabel('頻度', fontproperties=fp)
plt.show()
histogram3.pyの実行結果
histogram4.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# パラメータ
target = 'croatia.png'
# ヒストグラムの算出
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
hist = cv2.calcHist([img], [0], None, [64], [0, 256])
# 表示
fp = FontProperties(fname=r'C:\\WINDOWS\\Fonts\\msgothic.ttc', size=12)
val_x = []
val_y = []
for i in range(64):
val_x.append(i)
val_y.append(int(hist[i][0]))
plt.bar(np.array(val_x), np.array(val_y), color="#FF0000")
plt.title('ヒストグラム({0})'.format(target), fontproperties=fp)
plt.xlabel('ピクセル値', fontproperties=fp)
plt.ylabel('頻度', fontproperties=fp)
plt.show()
histogram4.pyの実行結果