直方图匹配又称为直方图规定化,是指将一幅图像的直方图变成规定形状的直方图而进行的图像增强方法。即将某幅影像或某一区域的直方图匹配到另一幅影像上。将图像的直方图分布规律与待匹配图像的脂肪分布规律近似。下面介绍两种方法:
1. 直方图匹配
def style_transfer(image, ref):
out = np.zeros_like(ref)
_, _, ch = image.shape
for i in range(ch):
print(i)
hist_img, _ = np.histogram(image[:, :, i], 256)
hist_ref, _ = np.histogram(ref[:, :, i], 256)
cdf_img = np.cumsum(hist_img)
cdf_ref = np.cumsum(hist_ref)
for j in range(256):
tmp = abs(cdf_img[j] - cdf_ref)
tmp = tmp.tolist()
idx = tmp.index(min(tmp)) # 找出tmp中最小的数,得到这个数的索引
out[:, :, i][ref[:, :, i] == j] = idx
return out
out = style_transfer(img, ref)
hist_img = cv2.calcHist([img], [0], None, [255], [0, 255])
hist_ref = cv2.calcHist([ref], [0], None, [255], [0, 255])
hist_out = cv2.calcHist([out], [0], None, [255], [0, 255])
plt.subplot(231)
plt.title("img")
plt.imshow(img)
plt.subplot(234)
plt.plot(hist_img)
plt.subplot(232)
plt.title("ref")
plt.imshow(ref)
plt.subplot(235)
plt.plot(hist_ref)
plt.subplot(233)
plt.title("out")
plt.imshow(out)
plt.subplot(236)
plt.plot(hist_out)
plt.show()
2. 针对灰度图优化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ref_gray = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
hist_ref = cv2.calcHist([ref_gray], [0], None, [256], [0, 256])
# 计算累计直方图
out = np.zeros_like(img)
tmp_ref = 0.0
h_ref = hist_ref.copy()
for i in range(256):
tmp_ref += h_ref[i]
h_ref[i] = tmp_ref
tmp = 0.0
h_acc = hist.copy()
for i in range(256):
tmp += hist[i]
h_acc[i] = tmp
# 计算映射
diff = np.zeros([256, 256])
for i in range(256):
for j in range(256):
diff[i][j] = np.fabs(h_ref[j] - h_acc[i])
M = np.zeros(256)
for i in range(256):
index = 0
min = diff[i][0] # min = 1.
for j in range(256):
if (diff[i][j] < min):
min = diff[i][j]
index = int(j)
M[i] = index
out = M[gray].astype(np.float32)
hist_img = cv2.calcHist([img], [0], None, [255], [0, 255])
hist_ref = cv2.calcHist([ref], [0], None, [255], [0, 255])
hist_out = cv2.calcHist([out], [0], None, [255], [0, 255])
plt.subplot(231)
plt.title("img")
plt.imshow(img)
plt.subplot(234)
plt.plot(hist_img)
plt.subplot(232)
plt.title("ref")
plt.imshow(ref)
plt.subplot(235)
plt.plot(hist_ref)
plt.subplot(233)
plt.title("out")
plt.imshow(out)
plt.subplot(236)
plt.plot(hist_out)
plt.show()