基礎ユニット2(イメージメディア) 第13回(2021/01/14)

関連サイトと資料

サンプル画像

island.jpg

wiki.jpg

cherry.jpg

サンプルプログラム

contrast1.py(ヒストグラム拡張)
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
	
def histogram_spread(hist, orgImg):
    h, w = orgImg.shape
    total = h * w
    sum = 0
    p_lower = 0
    p_upper = 0
    for i in range(256):
        sum += hist[i][0]
        if sum >= total * 0.01:
            p_lower = i
            break
    print(p_lower, sum, sum - hist[i][0], total*0.01)
  
    sum = 0
    for i in range(256):
        sum += hist[i][0]
        if sum >= total * 0.99:
            p_upper = i
            break
    print(p_upper, sum, sum - hist[i][0], total*0.99)
  
    eImg = orgImg.copy()
    for y in range(h):
        for x in range(w):
            if eImg[y,x] <= p_lower:
                eImg[y,x] = 0
            elif eImg[y,x] >= p_upper:
                eImg[y,x] = 255
            else:
                eImg[y,x] = int((eImg[y,x] - p_lower) * 255 / (p_upper - p_lower))
    
    hist2 = cv2.calcHist([eImg], [0], None, [256], [0, 256])
    return hist2, eImg
	
# パラメータ
target = 'island.jpg'
f3, f4 = os.path.splitext(target)
savename = f3 + '_spread' + f4
	
# ヒストグラムの算出とヒストグラム拡張
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
hist2, imgSpread = histogram_spread(hist, img)
cv2.imwrite(savename, imgSpread)
	
# 表示
fp = FontProperties(fname='C:\\WINDOWS\\Fonts\\msgothic.ttc', size=12)
val_x = []
val_y1 = []
val_y2 = []
for i in range(256):
    val_x.append(i)
    val_y1.append(int(hist[i][0]))
    val_y2.append(int(hist2[i][0]))
	
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
	
ax1.bar(np.array(val_x), np.array(val_y1), color="#FF0000")
ax1.set_title('ヒストグラム({0})'.format(target), fontproperties=fp)
ax1.set_xlabel('ピクセル値', fontproperties=fp)
ax1.set_ylabel('頻度', fontproperties=fp)
	
ax2.bar(np.array(val_x), np.array(val_y2), color="#FF0000")
ax2.set_title('ヒストグラム(ヒストグラム拡張した{0})'.format(target), fontproperties=fp)
ax2.set_xlabel('ピクセル値', fontproperties=fp)
ax2.set_ylabel('頻度', fontproperties=fp)
	
plt.show()
    

contrast1.pyの実行結果

island_spread.jpg

contrast2.py(ヒストグラム平坦化)
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
	
def histogram_equalization(hist, orgImg):
    h, w = orgImg.shape
    total = w * h
    lut = []
    sum = 0
    for i in range(256):
        sum += hist[i][0]
        v = int(255 * sum / total)
        lut.append(v)
    
    eImg = orgImg.copy()
    for y in range(h):
        for x in range(w):
            eImg[y,x] = lut[eImg[y,x]]
    
    hist2 = cv2.calcHist([eImg], [0], None, [256], [0, 256])
    return hist2, eImg
	
# パラメータ
target = 'cherry.jpg'
f3, f4 = os.path.splitext(target)
savename = f3 + '_equalization' + f4
	
# ヒストグラムの算出
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
hist2, imgEqualization = histogram_equalization(hist, img)
cv2.imwrite(savename, imgEqualization)
	
# 表示
fp = FontProperties(fname='C:\\WINDOWS\\Fonts\\msgothic.ttc', size=12)
val_x = []
val_y1 = []
val_y2 = []
for i in range(256):
    val_x.append(i)
    val_y1.append(int(hist[i][0]))
    val_y2.append(int(hist2[i][0]))
	
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
	
ax1.bar(np.array(val_x), np.array(val_y1), color="#FF0000")
ax1.set_title('ヒストグラム({0})'.format(target), fontproperties=fp)
ax1.set_xlabel('ピクセル値', fontproperties=fp)
ax1.set_ylabel('頻度', fontproperties=fp)
	
ax2.bar(np.array(val_x), np.array(val_y2), color="#FF0000")
ax2.set_title('ヒストグラム(ヒストグラム平坦化した{0})'.format(target), fontproperties=fp)
ax2.set_xlabel('ピクセル値', fontproperties=fp)
ax2.set_ylabel('頻度', fontproperties=fp)
	
plt.show()
    

contrast2.pyの実行結果

cherry_equalization.jpg

contrast2b.py(ヒストグラム平坦化/cv2.equalizeHist()を使用)
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
       
# パラメータ
target = 'cherry.jpg'
f3, f4 = os.path.splitext(target)
savename = f3 + '_equalization2' + f4
    
# 処理
img = cv2.imread(target, cv2.IMREAD_GRAYSCALE)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
img2 = cv2.equalizeHist(img)
hist2 = cv2.calcHist([img2], [0], None, [256], [0, 256])
cv2.imwrite(savename, img2)
    
# 表示
fp = FontProperties(fname='C:\\WINDOWS\\Fonts\\msgothic.ttc', size=12)
val_x = []
val_y1 = []
val_y2 = []
for i in range(256):
    val_x.append(i)
    val_y1.append(int(hist[i][0]))
    val_y2.append(int(hist2[i][0]))
    
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
    
ax1.bar(np.array(val_x), np.array(val_y1), color="#FF0000")
ax1.set_title('ヒストグラム({0})'.format(target), fontproperties=fp)
ax1.set_xlabel('ピクセル値', fontproperties=fp)
ax1.set_ylabel('頻度', fontproperties=fp)
    
ax2.bar(np.array(val_x), np.array(val_y2), color="#FF0000")
ax2.set_title('ヒストグラム(ヒストグラム平坦化した{0})'.format(target), fontproperties=fp)
ax2.set_xlabel('ピクセル値', fontproperties=fp)
ax2.set_ylabel('頻度', fontproperties=fp)
    
plt.show()
    

contrast2b.pyの実行結果

cherry_equalization2.jpg