10图片的灰度直方图
Tommy老师视频链接
# 1.直方图是图像中像素强度的分布的图形表达方式
# 2.直方图统计了每一个强度值素偶具有的像素个数
# 3.不表征任何纹理信息,具有平移不变形和缩放不变性等
# title等,暂不支持中文,无法显示
# 1.导入库
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 2.方法:显示图片
def show_image(image, title, pos):
# 顺序转换:GBR TO RGB
image_RGB = image[:, :, ::-1] # shape : (height, width, channel)
# test = [1, 2, 3]
# test1 = test[::-1]
# print(test1) # [3, 2, 1]
# 显示标题
plt.title(title)
plt.subplot(2, 3, pos) # 2列3行,pos位置
plt.imshow(image_RGB)
# 3.方法:显示图片的灰度直方图
def show_histogram(hist, title, pos, color):
plt.title(title)
plt.subplot(2, 3, pos) # 2列3行,pos位置
plt.xlabel('Bins')
plt.ylabel('Pixels')
plt.xlim([0, 256])
plt.plot(hist, color=color)
# 4.主函数 main()
def main():
# 创建画布
plt.figure(figsize=(15, 6)) # 画布大小
plt.suptitle('Gray Image Histogram', fontsize=14, fontweight='bold')
# 加载图片
img = cv2.imread('images/children.jpg')
# 灰度转换
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 8.计算灰度图的直方图 本张图已转化为灰度图所以channels为[0]
hist_img = cv2.calcHist([img_gray], [0], None, [256], [0, 256])
# 灰度转换BGR
img_BGR = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)
# 9.展示灰度直方图
show_image(img_BGR, 'BGR image', 1)
show_histogram(hist_img, 'gray image histogram', 4, 'm')
plt.show()
if __name__ == '__main__':
main()
别的也没啥说的
ok,那就这样吧~
欢迎各位大佬留言吐槽,也可以深入交流~