笔记和用法都在代码注释中:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('666.jpg',0) #0代表灰度图
img = cv.resize(img,(500,500))
hist = cv.calcHist([img],[0],None,[256],[0,256])
print(hist.shape)
#
# plt.hist(img.ravel(),256)
# plt.show()
# cv2.calcHist(images,channels,mask,histSize,ranges)
# Cv2.xxxxxxxxxx(图像、通道、掩膜、组织尺寸、范围)
#
# images:原图像图像格式为uint8或float32。当传入函数时应用中括号括来例如[img]
# channels:同样用中括号括来它会告函数我们统幅图像的直方图。
# omask:掩模图像。统整幅图像的直方图就把它为None。但是如果你想统图像某一分的直方图的你就制作一个掩模图像并使用它.
# histSize:BIN的数目。也应用中括号括来
# ranges:像素值范围常为[0256]
# -------------------------------------三原色通道统计分别打印!!!!
# img = cv.imread('666.jpg')
# color = ('b','g','r')
# for n,m in enumerate(color):
# hist = cv.calcHist([img],[n],None,[256],[0,256])
# plt.plot(hist,color = m)
# plt.xlim([0,256])
# plt.show()
# 创建mast
mask = np.zeros(img.shape[:2],np.uint8) #np.uint8 就是 0——255,
mask[100:1000,100:1800] = 255 #(x1:y1) ,(x2:y2) x1和x2是边框距离, y1(h) 和 y2(w) 是掩码大小
masked_img = cv.bitwise_and(img,img,mask=mask) #与操作
hist_full = cv.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv.calcHist([img],[0],mask,[256],[0,256])
plt.subplot(221),plt.imshow(img,'gray')
plt.subplot(222),plt.imshow(mask,'gray')
plt.subplot(223),plt.imshow(masked_img,'gray')
plt.subplot(224),plt.plot(hist_full),plt.plot(hist_mask)
plt.xlim([0,256])
plt.show()
#直方图均衡化 :
# 第一种:没有处理————————:
plt.hist(img.ravel(),256); #蓝色
# plt.show()
equ = cv.equalizeHist(img) #均衡化处理!!! (橙色!!!)
plt.hist(equ.ravel(),256)
plt.show() #直方图展示1!!
# 接下来: 对比图片,看看图片直方化的结果: (均衡化之后,感觉图像更亮了!!!【但是会丢失一些细节!!】)
# res = np.hstack((img,equ)) #左边的是原图像,右边是均衡化的!!!
# cv.imshow('res',res)
# cv.waitKey(0)
# cv.destroyAllWindows()
#均衡化优化处理 : 做均衡化局部处理:
clahe = cv.createCLAHE(clipLimit = 2.0, tileGridSize = (8,8)) #对图像做局部处理!!!
res_clahe = clahe.apply(img)
res = np.hstack((img,equ,res_clahe)) #结果:这样不仅像素均衡,并且图像不会损失太多细节!!
cv.imshow('res',res)
cv.waitKey(0)
cv.destroyAllWindows()