opencv——图像直方图(上)直方图分析

1、彩色直方图计算

#!/usr/bin env python3
# -*- coding:UTF8 -*-

# 彩色图像直方图的计算与显示
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('test.png')
cv2.imshow('SrcImage', img)
chans = cv2.split(img)
colors = ('b', 'g', 'r')
plt.title("’Flattened’ Color Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")

for (chan, color) in zip(chans, colors):
    hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
    plt.plot(hist, color=color)
    plt.xlim([0, 256])
plt.show()

2、灰度直方图转换

#!/usr/bin env python3
# -*- coding:UTF8 -*-

# 灰度直方图的计算与显示
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('test.png')

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

plt.imshow(img_gray, cmap=plt.cm.gray)

hist = cv2.calcHist([img], [0], None, [256], [0, 256])
print(type(hist))

# 创建一个新的子视图存放灰度图
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.plot(hist)

# 设置参数范围
plt.xlim([0, 256])
plt.show()

cv2.waitKey(0)
cv2.destroyAllWindows()

3、自定义函数实现灰度直方图计算

#!/usr/bin env python3
# -*- coding:UTF8 -*-


"""
    自定义函数实现灰度直方图计算
"""
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np

'''
    安装matplotlib指令:
    pip install matplotlib -i https://pypi.doubanio.com/simple
'''


def calcGrayHist(image):
    # 灰度图像矩阵的高、宽
    rows, cols = image.shape
    # 存储灰度直方图
    grayHist = np.zeros([256], np.uint64)
    for r in range(rows):
        for c in range(cols):
            grayHist[image[r][c]] += 1
    return grayHist


src = cv.imread('test.png', cv.IMREAD_GRAYSCALE)

cv.imshow("src", src)
# 计算灰度直方图
gray = calcGrayHist(src)
# 画出灰度直方图
x_range = range(256)
plt.plot(x_range, gray, 'r', linewidth=2, c='black')
# 设置坐标轴的范围
y_maxValue = np.max(gray)
plt.axis([0, 255, 0, y_maxValue])
# 设置坐标轴的标签
plt.xlabel('gray Level')
plt.ylabel('number of pixels')
# 显示灰度直方图
plt.show()

cv.waitKey(0)
cv.destroyAllWindows()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值