基礎ユニット2(イメージメディア) 第11回(2018/12/20)

関連サイトと資料

サンプル画像

bridge.png

Lenna.bmp

Airplane.bmp

couple.bmp

サンプルプログラム

colorContrastEnhancement1.py
import cv2
import os

def enhancer1(orgImg):
    関数の中身は各自で考える!
	
target = 'Lenna.bmp'
base, ext = os.path.splitext(target)
savename = base + '_contrast1.png' 
	
img = cv2.imread(target, cv2.IMREAD_COLOR)
img2 = enhancer1(img)
cv2.imwrite(savename, img2)
	
cv2.imshow('original', img)
cv2.imshow('contrast enhanced', img2)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

bridge_contrast1.png

Lenna_contrast1.png

colorContrastEnhancement2.py
import cv2
import os
	
def enhancer2(orgImg):
    関数の中身は各自で考える!
	
target = 'bridge.png'
base, ext = os.path.splitext(target)
savename = base + '_contrast2.png' 
	
img = cv2.imread(target, cv2.IMREAD_COLOR)
img2 = enhancer2(img)
cv2.imwrite(savename, img2)
	
cv2.imshow('original', img)
cv2.imshow('contrast enhanced', img2)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

bridge_contrast2.png

Lenna_contrast2.png

huePreserving.py
import cv2
import math
import numpy as np
import os
	
def createLUT(orgImg):
    h, w, _ = orgImg.shape
    hist = np.zeros(int(255*3+1), np.uint64)
    lut = np.zeros(int(255*3+1), np.uint16)
    
    for y in range(h):
        for x in range(w):
            blue, green, red = orgImg[y, x]
            index = float(blue) + float(green) + float(red)
            hist[int(index)] += 1
        
    sum = 0
    total = h * w
    for i in range(255*3+1):
        sum += hist[i]
        lut[i] = int(sum * 255 * 3 / total)
    return lut
	
def enhancer4(orgImg):
    small = 1e-5
    lut = createLUT(orgImg)

    h, w, _ = orgImg.shape
    enhancedImg = np.zeros_like(orgImg)
    
    for y in range(h):
        for x in range(w):
            blue, green, red = orgImg[y, x]
            lx = float(blue) + float(green) + float(red)
            alpha_lx = lut[int(lx)] / (lx + small)  
            
            if alpha_lx <= 1:
                blue2, green2, red2 = int(blue * alpha_lx), int(green * alpha_lx), int(red * alpha_lx)
                enhancedImg[y, x] = blue2, green2, red2
            else:
                elseの処理は各自で考える!
    
    return enhancedImg
	
target = 'Lenna.bmp'
base, ext = os.path.splitext(target)
savename = base + '_contrast_hp.png' 
	
img = cv2.imread(target, cv2.IMREAD_COLOR)
img2 = enhancer4(img)
cv2.imwrite(savename, img2)
	
cv2.imshow('original', img)
cv2.imshow('contrast enhanced with preserving hue', img2)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

bridge_contrast_hp.png

Lenna_contrast_hp.png