python 直方图匹配_Python OpenCV 直方图匹配

直方图匹配又称为直方图规定化,是指将一幅图像的直方图变成规定形状的直方图而进行的图像增强方法。即将某幅影像或某一区域的直方图匹配到另一幅影像上。将图像的直方图分布规律与待匹配图像的脂肪分布规律近似。下面介绍两种方法:

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值