(Python+OpenCV)绘制灰度直方图
绘制单通道直方图和RGB三通道直方图。IDE:Jupyter Lab#!/usr/bin/env python# coding: utf-8# In[13]:import sysimport cv2 as cvimport matplotlib.pyplot as plt# In[14]:print('Python的版本为:Python',sys.version_info.major)print(
·
绘制单通道直方图和RGB三通道直方图。
IDE:Jupyter Lab
#!/usr/bin/env python
# coding: utf-8
# In[13]:
import sys
import cv2 as cv
import matplotlib.pyplot as plt
# In[14]:
print('Python的版本为:Python',sys.version_info.major)
print('OpenCV的版本为:',cv.__version__)
# In[15]:
#图片路径
#(应避免有中文)
image_path=r'C:\Users\94456\Desktop\test2020_09_03\picture\cat.jpg'
# In[16]:
#读取图片
#类型:numpy.ndarray
image=cv.imread(image_path)
# In[17]:
#显示原图
cv.namedWindow('cat',cv.WINDOW_NORMAL)
cv.resizeWindow('cat',200,200)
cv.imshow('cat',image)
cv.waitKey(0)
# In[18]:
#使用 ravel 拉直图像
#ravel:将多维矩阵降为一维矩阵
image_ravel=image.ravel()
# In[19]:
#对比降维前和降维后的矩阵
print('降维前的尺寸:',image.shape)
print('降维后的尺寸:',image_ravel.shape)
# In[27]:
get_ipython().run_line_magic('matplotlib', 'auto')
#显示灰度直方图
plt.hist(image_ravel,256,[0,256])
plt.show()
# In[29]:
get_ipython().run_line_magic('matplotlib', 'auto')
color=['blue','green','red']
for i,color_sub in enumerate(color):
#要计算的图
#要计算的维度
#要计算的区域ROI,计算整图则为None
#子区段数目
#要计算的像素范围
hist=cv.calcHist([image],[i],None,[256],[0,256])
plt.plot(hist,color=color_sub)
plt.xlim([0,256])
plt.show()
# In[ ]:
原图:
对原图进行降维:
直方图:
RGB三通道直方图:
更多推荐
已为社区贡献9条内容
所有评论(0)