-
图像处理中绘制图像直方图往往是观察和处理图像的利器之一。
-
直方图的观察方面的基本知识:
- 横坐标代表着灰度级、纵坐标是该灰度值在图像中出现的概率或者次数。
- 直方图的型态为斜态和峰态,斜态指的是直方图的不对称的程度,峰态表示的是直方图的分布在均值周围的集中程度。
- 直方图可以基本上反映出图像对比度的基本情况。
-
直方图的基本性质
- 直方图没有位置信息。
- 直方图反映了总体灰度分布。
- 直方图具有可叠加性。
- 直方图具有统计性。
不多BB,上代码:
实现一:
from PIL import Image
from pylab import *
import cv2
from tqdm import tqdm
def Rgb2gray(image):
h = image.shape[0]
w = image.shape[1]
grayimage = np.zeros((h,w),np.uint8)
for i in tqdm(range(h)):
for j in range(w):
grayimage [i,j] = 0.144*image[i,j,0]+0.587*image[i,j,1]+0.299*image[i,j,1]
return grayimage
# 读取图像到数组中,并灰度化
image = cv2.imread("peng.png")
im = array(Image.open('peng.png').convert('L'))
# 直方图图像
# flatten可将二维数组转化为一维
hist(image.flatten(), 128)
# 显示
show()
显示效果图如下:
实现方法二:
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
import os
import pandas as pd
from tqdm import tqdm
# 绘制直方图函数
def grayHist(img):
h, w = img.shape[:2]
pixelSequence = img.reshape([h * w, ])
numberBins = 256
histogram, bins, patch = plt.hist(pixelSequence, numberBins,
facecolor='black', histtype='bar')
plt.xlabel("gray label")
plt.ylabel("number of pixels")
plt.axis([0, 255, 0, np.max(histogram)])
plt.show()
image = cv2.imread("peng.png",0)
grayHist(image)
显示效果如下: