© Fu Xianjun. All Rights Reserved.
练习1:绘制彩色的直方图
import cv2
import numpy as np
img=cv2.imread("bd.jpg")
histb = cv2.calcHist([img],[0],None,[256],[0,255])
histg = cv2.calcHist([img],[1],None,[256],[0,255])
histr = cv2.calcHist([img],[2],None,[256],[0,255])
plt.plot(histb,color='b')
plt.plot(histg,color='g')
plt.plot(histr,color='r')
练习1.1 彩色直方图封装¶
import cv2
import numpy as np
from matplotlib import pyplot as plt
def image_hist(image):
color = ('blue', 'green', 'red')
for i, color in enumerate(color):
hist = cv2.calcHist([image], [i], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
plt.show()
img=cv2.imread("bd.jpg")
image_hist(img)
练习2:使用掩膜进行直方图绘制
import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread("hj.jpg",0)
w,h=img.shape
mask=np.zeros([w,h],np.uint8)
mask[(w-200):w,0:200]=255
hist = cv2.calcHist([img],[0],None,[256],[0,255])
hist_mask = cv2.calcHist([img],[0],mask,[256],[0,255])
# cv2.imshow('mask',mask)
plt.plot(hist,color='b')
plt.plot(hist_mask,color='g')
cv2.waitKey()
cv2.destroyAllWindows()
练习3:彩色图像直方图均衡化
import cv2
import numpy as np
img=cv2.imread("qb.jpg")
b,g,r=cv2.split(img)
equb=cv2.equalizeHist(b)
equg=cv2.equalizeHist(g)
equr=cv2.equalizeHist(r)
img_new=cv2.merge([equb,equg,equr])
histb = cv2.calcHist([img_new],[0],None,[256],[0,255])
histg = cv2.calcHist([img_new],[1],None,[256],[0,255])
histr = cv2.calcHist([img_new],[2],None,[256],[0,255])
plt.plot(histb,color='b')
plt.plot(histg,color='g')
plt.plot(histr,color='r')
cv2.imshow("img",img)
cv2.imshow("img_new",img_new)
cv2.waitKey()
cv2.destroyAllWindows()