图像直方图指的是描述图像的强度分布,一般来说横轴为0-255,纵轴为横轴像素值对应的像素个数。
img = cv.imread('XXX')
hist = cv.calcHist([img],[0],None,[256],[0,256])
参数说明:
import cv2
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread(r'XXXXX')
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
hist_full = cv.calcHist([img],[0],None,[256],[0,256] )
plt.subplot(121), plt.imshow(img, 'gray')
plt.subplot(122), plt.plot(hist_full)
plt.show()
(其实我认为实现这个功能,直接截取原图像生成新,再运用上述方法会更简单易懂)
import cv2
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread(r'XXXX')
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 创建一个掩码
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:400, 100:400] = 255
masked_img = cv.bitwise_and(img,img,mask = mask)
# 计算带掩膜和不带掩膜的直方图
# 检查第三个参数的掩膜
hist_full = cv.calcHist([img],[0],None,[256],[0,256] )
hist_mask = cv.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),plt.plot(hist_mask)
plt.show()
原理即matlab实现:
图像均衡化---MATLAB实现_独憩的博客-CSDN博客
opencv实现:
equ = cv.equalizeHist(img)
import cv2
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread(r'XXXX')
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
hist1 = cv.calcHist([img], [0], None, [256], [0, 256])
equ = cv.equalizeHist(img)
hist2 = cv.calcHist([equ], [0], None, [256], [0, 256])
res = np.hstack((img, equ)) # stacking images side-by-side
plt.imshow(res, 'gray')
plt.show()
plt.figure(2)
plt.subplot(1,2,1)
plt.plot(hist1)
plt.subplot(1,2,2)
plt.plot(hist2)
可以看到,均衡化之后的图片有部分地方太亮,丢失了一些信息,故我们可以OpenCV 中应用 CLAHE。
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl1 = clahe.apply(img)
原理简单来说就是给原图像划分了许多小方块,大小由tileGridSize决定,每个小方块内部都独立进行均衡化处理。
import cv2
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread(r'XXXXX')
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
hist1 = cv.calcHist([img], [0], None, [256], [0, 256])
equ = cv.equalizeHist(img)
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl1 = clahe.apply(img)
hist2 = cv.calcHist([equ], [0], None, [256], [0, 256])
hist3 = cv.calcHist([cl1], [0], None, [256], [0, 256])
res = np.hstack((img,cl1, equ)) # stacking images side-by-side
plt.imshow(res, 'gray')
plt.show()
plt.figure(2)
plt.subplot(1,3,1)
plt.plot(hist1)
plt.subplot(1,3,2)
plt.plot(hist2)
plt.subplot(1,3,3)
plt.plot(hist3)
plt.show()