PROGRAMMING

히스토그램 평준화, CLAHE 본문

OpenCV/머신비전 - 이미지 디텍팅

히스토그램 평준화, CLAHE

Raccoon2125 2021. 1. 14. 09:16
import cv2
import numpy as np

bins = np.arange(256).reshape(256, 1)

def draw_histogram(img):

    h = np.zeros((img.shape[0], 256), dtype = np.uint8)

    hist_item = cv2.calcHist([img], [0], None, [256], [0, 256])
    cv2.normalize(hist_item, hist_item, 0, 255, cv2.NORM_MINMAX)
    hist = np.int32(np.around(hist_item))
    for x, y in enumerate(hist):
        cv2.line(h, (x, 10), (x, int(y) + 10), (255, 255, 255))
    
    cv2.line(h, (0, 10), (0, 5), (255, 255, 255))
    cv2.line(h, (255, 10), (255, 5), (255, 255, 255))
    y = np.flipud(h)
    
    hist, bin = np.histogram(img.flatten(), bins = 256, range = [0, 256])
    cdf = hist.cumsum()
    cdf_normalized = cdf * float(hist.max()) / cdf.max()
    cv2.normalize(cdf_normalized, cdf_normalized, 0, 255, cv2.NORM_MINMAX)
    hist = np.int32(np.around(cdf_normalized))
    pts = np.int32(np.column_stack((bins, hist)))
    pts += [257, 10]

    cv2.line(h, (257, 10), (257, 5), (255, 255, 255))
    cv2.line(h, (255+257, 10), (255+257, 5), (255, 255, 255))
    cv2.polylines(h, [pts], False, (255,255,255))

    return y

img = cv2.imread('OpenCV/images/pawns.jpg', cv2.IMREAD_ANYCOLOR)
img = cv2.resize(img, dsize = (0, 0), fx = 0.5, fy = 0.5)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

line = draw_histogram(gray)
result1 = np.hstack((gray, line))
cv2.imshow('result1', result1)

# 히스토그램, 평활화, 마스크(필터), 재변환.
# hist, bin = np.histogram(img.flatten(), bins = 256, range = [0, 256])
# cdf = hist.cumsum()
# cdf_mask = np.ma.masked_equal(cdf, 0) # cdf의 값이 0인 경우 mask 처리하여 계산 제외
# cdf_mask = (cdf_mask - cdf_mask.min())*255/(cdf_mask.max() - cdf_mask.min()) # 계산
# cdf = np.ma.filled(cdf_mask, 0).astype('uint8') # mask처리한 부분을 0으로 재변환
# equ = cdf[gray]

# 위의 주석된 6줄이 아래 한 줄로 가능
#equ = cv2.equalizeHist(gray)

clahe = cv2.createCLAHE(clipLimit = 2.0, tileGridSize = (8, 8))
equ = clahe.apply(gray)

line = draw_histogram(equ)
result2 = np.hstack((equ, line))
cv2.imshow('result2', result2)

cv2.waitKey(0)
cv2.destroyAllWindows()

pawns.jpg
0.25MB
평준화 이전
평준화 이후 (CLAHE 적용)

'OpenCV > 머신비전 - 이미지 디텍팅' 카테고리의 다른 글

YOLO(Object Tracking)  (0) 2021.01.14
YOLO (Selective Search, IOU)  (0) 2021.01.14
YOLO(Game 결과 이미지)  (0) 2021.01.02
YOLO(Darknet Setup - Colab / cuDNN)  (0) 2021.01.02
YOLO(Game)  (0) 2021.01.02
Comments