图像直方图
cv2.calcHist(images,channels,mask,histSize,ranges)会输出每一个灰度值对应的像素数目
- images:原图像图像格式为uint8或float32。当传入函数时应用中括号[]括起来
- channels:输入图像的通道,同样用中括号括起来,如果输入图像是灰度图像就是[0],如果是彩色图像,可以是[0][1][2]分别表示BGR。
- mask:掩模图像。一个大小与image一样的numpy数组,把需要处理的部分指定为1,不需要处理的地方处理为0,如果要处理整幅图像,就设置为None
- histSize:BIN(柱子)的数目,也需要用中括号括起来
- ranges:像素值的范围,一般为[0,256]
import cv
import matplotlib.pyplot as plt
img = cv2.imread('image/image4.png')
hist = cv2.calcHist([img],[0],None,[256],[0,256])
print(hist.shape)
cv2.imshow('img',img)
plt.plot(hist,color = 'g')
plt.xlim([0,256])
plt.show()
输出结果:
不同通道的输入:
color = ('b','g','r')
for i,col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
输出结果:
mask操作
掩模是一张只由黑白两色组成的图像,即其灰度值只有0和255,通过numpy生成一个全为0的数组,将其中需要处理的部分置为1。
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('image/image4.png')
cv2.imshow('img',img)
mask = np.zeros(img.shape[:2],np.uint8)
mask[100:200,100:200] = 255
cv2.imshow('mask',mask)
masked_img = cv2.bitwise_and(img,img,mask = mask)
cv2.imshow('masked_img',masked_img)
hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv2.calcHist([img],[0],mask,[256],[0,256])
plt.plot(hist_full),plt.plot(hist_mask)
plt.xlim([0,256])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
输出结果:
原图
mask图:
原图添加mask后图片:
直方图:
均衡化
部分图像在某些灰度值的位置像素点特别多,可以对其进行均衡化处理。
均衡化是一种增强图像对比度的方法,其主要思想是将一副图像的直方图分布通过累积分布函数变成近似均匀分布,从而增强图像的对比度。为了将原图像的亮度范围进行扩展, 需要一个映射函数, 将原图像的像素值均衡映射到新直方图中, 这个映射函数有两个条件:
- 不能打乱原有的像素值大小顺序、不能改变映射后的亮暗的大小关系
- 映射后必须在原有的范围内
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('image/image5.png',0)
cv2.imshow('img',img)
plt.hist(img.ravel(),256)
plt.show()
equ = cv2.equalizeHist(img)
plt.hist(equ.ravel(),256)
plt.show()
cv2.imshow('equ',equ)
res = np.hstack((img,equ))
cv2.imshow('res',res)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出结果:
均衡化前
均衡化后:
图像对比:
均衡化之后图片更加明亮,但细节会有缺失。
自适应均衡化
clahe = cv2.createCLAHE(clipLimit = 2.0,tileGridSize=(8, 8))
res_clahe = clahe.apply(img)
res = np.hstack((img,equ,res_clahe))
cv2.imshow('res',res)
cv2.imwrite('res.jpg',res)