使用OpenCV,Numpy计算直方图,Matplot绘制直方图及分析

更新时间:2023-07-20 18:52:11 阅读: 评论:0

使⽤OpenCV,Numpy计算直⽅图,Matplot绘制直⽅图及分析
使⽤OpenCV,Numpy计算直⽅图,Matplot绘制直⽅图及分析
这篇博客将介绍如何使⽤Python,OpenCV,Numpy函数计算直⽅图,并使⽤ OpenCV 和 Matplotlib 函数绘制直⽅图,并对直⽅图进⾏分析。
通过查看图像的直⽅图,可以直观地了解该图像的对⽐度、亮度、强度分布等。
大白头像
1. 效果图
原始图如下:
灰度图直⽅图效果如下:
可以看到左侧区域显⽰图像中较暗像素的数量,右侧区域显⽰较亮像素的数量。从直⽅图中可以看到暗区、亮区均不多,并且中间⾊调(中间范围的像素值,例如 170/210 左右)的数量⾮常多。
BGR三通道的直⽅图效果图下:
原始图 VS Mask遮罩 VS Mask图像 VS 混合直⽅图如下:
在第4个直⽅图中,蓝线表⽰完整图像的直⽅图,红线表⽰遮罩区域的直⽅图。
2. 原理
直⽅图可以帮助全⾯了解图像的强度分布。 最基本的直⽅图是灰度图像直⽅图,在 X 轴上具有像素值(范围从 0 到 255)和 Y 轴上图像中相应像素数的图。
计算直⽅图的3种⽅式:
国际汇兑hist = cv2.calcHist([img],[0],None,[256],[0,256])
hist,bins = np.histogram(img.ravel(),256,[0,256])
np.bincount(img.ravel(),minlength=256)
其中cv2的⽅式⽐np.histogram快40倍;
np.bincount⽐np.histogram快10倍,因此优先使⽤cv2.calHist()⽅式;
绘制直⽅图的2种⽅式:
matplot计算直⽅图并绘制:plt.hist(img.ravel(),256,[0,256]); plt.show()
matplot的简单绘制⽅式:histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
3. 源码
3.1 直⽅图3种计算⽅法和2种绘制⽅法
import cv2
右倒库import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('ml.jpg',0)
# cv计算直⽅图
直角三角形公式
# cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) # - img:要计算直⽅图的图像
# - channels:通道值,如果传⼊灰度图为0,彩⾊图[0][1][2]分别计算BGR通道# - mask:蒙版,并⾮为整个图计算直⽅图
# - histSize:x轴分多少个范围
# - ranges: 值的范围,通常是[0,256]
hist = cv2.calcHist([img],[0],None,[256],[0,256])
# numpy计算直⽅图
逛街去
#  np.bincount() ⽐ np.histogram() ⼤概快10倍
#  cv2.calHist() ⽐ np.histogram() ⼤概快40倍
hist, bins = np.histogram(img.ravel(),256,[0,256])
hist = np.bincount(img.ravel(), minlength=256)
# 绘制直⽅图法1:matplot
img = cv2.imread('ml.jpg',0)
plt.hist(img.ravel(),256,[0,256])
plt.show()
# 绘制直⽅图法2:matplot普通绘制⽅式
img = cv2.imread('ml.jpg')
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()
3.2 Mask遮罩图像直⽅图
鲁迅白光
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('ml.jpg',0)
# 构造⼀个mask
陪你到天涯海角mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300,100:400]=255
masked_img = cv2.bitwi_and(img, img, mask=mask)
# 计算整个图直⽅图以及mask的直⽅图
hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv2.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, color='b'), plt.plot(hist_mask, color='r') plt.xlim([0,256])
克孜尔水库plt.show()
参考

本文发布于:2023-07-20 18:52:11,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1089465.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:图像   像素   区域   分布   了解
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图