Python图像处理(二)【直方图均衡化】

1.直方图均衡化

在这里插入图片描述
获取图片及显示图片的通用方法如下:

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

#获取图片
def getimg():
  return Image.open("f:/pic/timg.jpg")
  
#显示图片
def showimg(img, isgray=False):
  plt.axis("off")
  if isgray == True:
    plt.imshow(img, cmap='gray')
  else: 
    plt.imshow(img)
  plt.show()

直方图均衡化方法

def histeq(imarr):
  hist, bins = np.histogram(imarr, 255)
  cdf = np.cumsum(hist)
  cdf = 255 * (cdf/cdf[-1])
  res = np.interp(imarr.flatten(), bins[:-1], cdf)
  res = res.reshape(imarr.shape)
  return res, hist

1.1.灰度图像均衡化

在这里插入图片描述

img = getimg()
gray_image = img.convert('L')
gray_arr = np.array(gray_image)
res,hist = histeq(gray_arr)
showimg(Image.fromarray(res))

1.2.彩色图像均衡化

在这里插入图片描述

1.2.1.合并RGB三通道像素的直方图均衡化

在这里插入图片描述

def rgb_histeq1(im):
  imarr = np.array(im)
  imarr2 = imarr.flatten()
  hist, bins = np.histogram(imarr2, 255)
  cdf = np.cumsum(hist)
  cdf = 255* (cdf/cdf[-1])
  imarr3 = np.interp(imarr2, bins[:-1], cdf)
  imarr3 = imarr3.reshape(imarr.shape)
  return Image.fromarray(imarr3.astype('uint8'), mode='RGB')

img2 = rgb_histeq1(img)
showimg(img2)

1.2.2.RGB三通道各自均衡化

在这里插入图片描述

def rgb_histeq2(im):
  imarr = np.array(im)
  r_arr = imarr[...,0]
  g_arr = imarr[...,1]
  b_arr = imarr[...,2]
  
  r_res, r_hist = histeq(r_arr)
  g_res, g_hist = histeq(g_arr)
  b_res, b_hist = histeq(b_arr)
  
  new_imarr = np.zeros(imarr.shape, dtype='uint8')
  new_imarr[...,0] = r_res
  new_imarr[...,1] = g_res
  new_imarr[...,2] = b_res
  
  return Image.fromarray(new_imarr, mode='RGB')

img = getimg()
img3 = rgb_histeq2(img)
showimg(img3)

1.2.3.取RGB三通道像素平均值的直方图均衡化

在这里插入图片描述

def rgb_histeq3(im):
  imarr = np.array(im)
  r_arr = imarr[...,0]
  g_arr = imarr[...,1]
  b_arr = imarr[...,2]
  
  #取三个通道的平均值
  imarr2 = np.average(imarr, axis=2)
  hist, bins = np.histogram(imarr2, 255)
  cdf = np.cumsum(hist)
  cdf = 255 * (cdf/cdf[-1])
  
  r_res = np.interp(r_arr, bins[:-1], cdf)
  g_res = np.interp(g_arr, bins[:-1], cdf)
  b_res = np.interp(b_arr, bins[:-1], cdf)
  
  new_imarr = np.zeros(imarr.shape, dtype="uint8")
  new_imarr[...,0] = r_res
  new_imarr[...,1] = g_res
  new_imarr[...,2] = b_res
  
  return Image.fromarray(new_imarr, mode='RGB')
  
img = getimg()
img4 = rgb_histeq3(img)
showimg(img4)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值