https://mp.weixin.qq.com/s/ZKszOcPDTe4TUsLZwsx4mw
1、颜色直方图
单张图像 绘制颜色直方图-三通道直方图 绘制到一张图
#-------------------------------单张图像 绘制颜色直方图-三通道直方图-----
import cv2
import numpy as np
import matplotlib.pyplot as plt
def plot_demo(image):
plt.hist(image.ravel(),256,[0,256])
plt.show("直方图")
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.show()
if __name__ == '__main__':
image=cv2.imread('../opencv-python-img/lena.png')
#plot_demo(image)
image_hist(image)
批量 绘制三通道直方图
import cv2
import numpy as np
import os
def ImageHist(image,type):
color=(255,255,255)
if type==31:
color=(255,0,0)
windowName='B hist'
elif type==32:
color=(0,255,0)
windowName='G hist'
elif type==33:
color=(0,0,255)
windowName='R hist'
#1 image 2 通道 3 mask None 4 256种灰度值 5 0-255
hist = cv2.calcHist([image],[0],None,[256],[0.0,255.0])
minV, maxV,minL,maxL=cv2.minMaxLoc(hist)
histImg=np.zeros([256,256,3],np.uint8)
for h in range(256):
intenNormal=int(hist[h]*256/maxV)
cv2.line(histImg,(h,256),(h,256-intenNormal),color)
cv2.imshow(windowName,histImg)
return histImg
if __name__=="__main__":
path='../data/person/img/'
for file in os.listdir(path):
file_path=os.path.join(path,file)
img=cv2.imread(file_path,1)
cv2.imshow('img',img)
channels=cv2.split(img)
for i in range(0,3):
imghist=ImageHist(channels[i],31+i)
cv2.imwrite('../data/result/rgb_hist/'+file.split('.')[0]+'__'+str(i)+'.jpg',imghist)
cv2.waitKey(5000)
批处理 绘制图像的直方图 灰度通道
################循环绘制文件夹中的图像的直方图 灰度通道##########################
#! -*- coding: utf-8 -*-
import numpy as np
import cv2
import os
from os import listdir
from tqdm import tqdm
import matplotlib.pyplot as plt
# 定义输入文件夹路径和输出文件夹路径
input_folder = '../data/person/img/'
output_folder = '../data/result/hist_gray/'
if not os.path.exists(output_folder):
os.mkdir(output_folder)
# 获取输入文件夹内所有文件名
file_names = os.listdir(input_folder)
for file_name in file_names:
# 构建完整的输入文件路径和输出文件路径
input_path = os.path.join(input_folder, file_name)
print(1111111,input_path)
output_path = os.path.join(output_folder, file_name[:-4] + '_hist.jpg')
# 读取彩色图像并进行灰度化处理
image = cv2.imread(input_path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
hist_frame = cv2.calcHist([gray_image],[0],None,[256],[0,255])
plt.plot(hist_frame,color='b')
plt.grid(True)
plt.rcParams['font.sans-serif'] = ['Kaitt', 'SimHei']
plt.xlabel("亮度")
plt.ylabel("像素")
plt.savefig(output_path)
#plt.show()
plt.close()
#cv2.imshow("gray_image",gray_image)
#cv2.imshow("hist_frame",hist_frame)
#cv2.waitKey(1000)
# 保存灰度图像到指定位置
#cv2.imwrite(output_path, hist_frame)
2、直方图均衡化+直方图比较
#------------------直方图均衡化,直方图比较-----------
import cv2
import numpy as np
import matplotlib.pyplot as plt
#直方图均衡化
def equalHist_demo(image):
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
dst=cv2.equalizeHist(gray)
#cv2.equalizeHist(img),将要均衡化的原图像【要求是灰度图像】作为参数传入,则返回值即为均衡化后的图像
cv2.imshow('equalHist_demo',dst)
# CLAHE 图像增强方法主要用在医学图像上面,增强图像的对比度的同时可以抑制噪声,是一种对比度受限情况下的自适应直方图均衡化算法
# 图像对比度指的是一幅图片中最亮的白和最暗的黑之间的反差大小。
def clahe_demo(image):
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
clahe=cv2.createCLAHE(clipLimit=5.0,tileGridSize=(8,8))
dst=clahe.apply(gray)
cv2.imshow('clahe_demo',dst)
def create_rgb_hist(image):
#创建RGB三通道直方图(直方图矩阵)
#16*16*16的意思是三通道的每通道有16个bins
h,w,c=image.shape
rgbHist=np.zeros([16*16*16,1],np.float32)
bsize=256/16
for row in range(h):
for col in range(w):
b=image[row,col,0]
g=image[row,col,1]
r=image[row,col,2]
#人为构建直方图矩阵的索引,该索引是通过每一个像素点的三通道值进行构建
index=np.int(b/bsize)*16*16+np.int(g/bsize)+np.int(r/bsize)
#该处形成的矩阵即为直方图矩阵
rgbHist[np.int(index),0]=rgbHist[np.int(index),0]+1
plt.ylim([0,10000])
plt.grid(color='r',linestyle='--',linewidth=0.5,alpha=0.3)
return rgbHist
#直方图比较
def hist_compare(image1,image2):
hist1=create_rgb_hist(image1)
hist2=create_rgb_hist(image2)
match1=cv2.compareHist(hist1,hist2,cv2.HISTCMP_BHATTACHARYYA)
match2=cv2.compareHist(hist1,hist2,cv2.HISTCMP_CORREL)
match3=cv2.compareHist(hist1,hist2,cv2.HISTCMP_CHISQR)
print('巴氏距离:%s,相关性:%s,卡方:%s'%(match1,match2,match3))
#巴氏距离比较(method=cv2.HISTCMP_BHATTACHARYYA)值越小,相关度越高[0,1]
#相关性(method=cv2.HISTCMP_CORREL)值越大,相关度越高,[0,1]
#卡方(method=cv2.HISTCMP_CHISQR),值越小,相关度越高,[0,inf)
if __name__ == '__main__':
#image=cv2.imread('../opencv-python-img/lena.png')
#cv2.imshow('origin_image',image)
#equalHist_demo(image)
#clahe_demo(image)
image1=cv2.imread('../opencv-python-img/lena.png')
image2=cv2.imread('../opencv-python-img/lenanoise.png')
plt.subplot(1,2,1)
plt.title('diff1')
plt.plot(create_rgb_hist(image1))
plt.subplot(1,2,2)
plt.title('diff2')
plt.plot(create_rgb_hist(image2))
plt.show()
hist_compare(image1,image2)
#cv2.waitKey(0)
批处理,灰度图直方图均衡化
#! -*- coding: utf-8 -*-
import numpy as np
import cv2
import os
from os import listdir
from tqdm import tqdm
def Histogram(image):#直方图 可以处理彩色图像
hist,bins = np.histogram(image.flatten(),256,[0,256])#img.flatten将数组变成一维数组
cdf = hist.cumsum()#计算直方图
cdf_normalized = cdf * hist.max()/ cdf.max()
cdf_m = np.ma.masked_equal(cdf,0)
cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
# 对被掩盖的元素赋值,这里赋值为 0
cdf = np.ma.filled(cdf_m,0).astype('uint8')
Histogram_img = cdf[image]
return Histogram_img
# 定义输入文件夹路径和输出文件夹路径
input_folder = '../data/person/img/'
output_folder = '../data/result/hist_gray/'
if not os.path.exists(output_folder):
os.mkdir(output_folder)
# 获取输入文件夹内所有文件名
file_names = os.listdir(input_folder)
for file_name in file_names:
# 构建完整的输入文件路径和输出文件路径
input_path = os.path.join(input_folder, file_name)
print(1111111,input_path)
output_path = os.path.join(output_folder, file_name[:-4] + '_hist.jpg')
# 读取彩色图像并进行灰度化处理
image = cv2.imread(input_path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
hist_frame = Histogram(gray_image)
#cv2.imshow("gray_image",gray_image)
#cv2.imshow("hist_frame",hist_frame)
#cv2.waitKey(1000)
# 保存灰度图像到指定位置
cv2.imwrite(output_path, hist_frame)
cv2.destroyAllWindows()
灰度图直方图均衡化后的直方图分布
#! -*- coding: utf-8 -*-
import numpy as np
import cv2
import os
from os import listdir
from tqdm import tqdm
import matplotlib.pyplot as plt
def hist_equal(img, z_max=255):
H, W, C = img.shape
S = H * W * C * 1.
out = img.copy()
sum_h = 0.
for i in range(1, 255):
ind = np.where(img == i)
sum_h += len(img[ind])
z_prime = z_max / S * sum_h
out[ind] = z_prime
out = out.astype(np.uint8)
return out
# 定义输入文件夹路径和输出文件夹路径
input_folder = '../data/person/img/'
output_folder = '../data/result/eqhist/'
if not os.path.exists(output_folder):
os.mkdir(output_folder)
# 获取输入文件夹内所有文件名
file_names = os.listdir(input_folder)
for file_name in file_names:
# 构建完整的输入文件路径和输出文件路径
input_path = os.path.join(input_folder, file_name)
print(1111111,input_path)
output_path = os.path.join(output_folder, file_name[:-4] + '_eqhist.jpg')
# 读取彩色图像并进行灰度化处理
image = cv2.imread(input_path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_image = cv2.equalizeHist(gray_image) #直接调用直方图均值化函数
#hist_frame = hist_equal(image) #调用自己写的函数 绘制直方图
#hist_frame = cv2.calcHist([gray_image],[0],None,[256],[0,255])
plt.hist(gray_image.ravel(),histtype="bar",bins=50,rwidth=0.5,range=(0, 255))#函数ravel()拉直图像 设置直方图间距等
plt.rcParams['font.sans-serif'] = ['Kaitt', 'SimHei']
plt.xlabel("亮度")
plt.ylabel("像素")
plt.xticks(np.arange(5,255,10),fontsize=10,rotation=90)
plt.yticks(fontsize=12)
#plt.gca().set_axis_off()
#plt.axis('off')
#plt.bar([0,255],gray_image.ravel(),width=0.5)
#plt.bar(range(len(hist_frame)),hist_frame/float(sum(hist_frame)))
#plt.plot(hist_frame,color='b')
#plt.grid(True)
plt.savefig(output_path)
#plt.show()
plt.close()
#cv2.imshow("gray_image",gray_image)
#cv2.imshow("hist_frame",hist_frame)
#cv2.waitKey(1000)
# 保存灰度图像到指定位置
#cv2.imwrite(output_path, hist_frame)
批处理彩图直方图均衡化处理,两种方法
调用Histogram函数或者调用equalizeHist函数处理hsv颜色模型的v通道
#! -*- coding: utf-8 -*-
import numpy as np
import cv2
import os
from os import listdir
from tqdm import tqdm
def Histogram(image):#直方图均衡化 可以处理彩色图像
hist,bins = np.histogram(image.flatten(),256,[0,256])#img.flatten将数组变成一维数组
cdf = hist.cumsum()#计算累积直方图
cdf_normalized = cdf * hist.max()/ cdf.max()
cdf_m = np.ma.masked_equal(cdf,0)#对于掩码数组,所有操作都在非掩码元素上执行
cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
# 对被掩盖的元素赋值,这里赋值为 0
cdf = np.ma.filled(cdf_m,0).astype('uint8')
Histogram_img = cdf[image]
return Histogram_img
# 定义输入文件夹路径和输出文件夹路径
input_folder = '../data/person/img/'
output_folder = '../data/result/eq_rgb/'
if not os.path.exists(output_folder):
os.mkdir(output_folder)
# 获取输入文件夹内所有文件名
file_names = os.listdir(input_folder)
for file_name in file_names:
# 构建完整的输入文件路径和输出文件路径
input_path = os.path.join(input_folder, file_name)
print(1111111,input_path)
output_path = os.path.join(output_folder, file_name[:-4] + '_hist_hsv.jpg')
# 读取彩色图像并进行灰度化处理
image = cv2.imread(input_path)
#gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
v2 = cv2.equalizeHist(v)#输入只能是灰度图像,单通道
img2 = cv2.merge([h, s, v2])
hist_frame = cv2.cvtColor(img2, cv2.COLOR_HSV2BGR)
#hist_frame = Histogram(image)#或者使用该方法进行彩图的直方图均衡化处理
#cv2.imshow("gray_image",gray_image)
#cv2.imshow("hist_frame",hist_frame)
#cv2.waitKey(1000)
# 保存灰度图像到指定位置
cv2.imwrite(output_path, hist_frame)
cv2.destroyAllWindows()
3、直方图反向投影
#-----------------------------------------------直方图反向投影-------------------------------
import cv2
import numpy as np
import matplotlib.pyplot as plt
#1、HSV与RGB色彩空间
#2、反向投影
def back_projection_demo():
sample=cv2.imread('../opencv-python-img/lena.png')
target=cv2.imread('../opencv-python-img/lenanoise.png')
roi_hsv=cv2.cvtColor(sample,cv2.COLOR_BGR2HSV)
target_hsv=cv2.cvtColor(target,cv2.COLOR_BGR2HSV)
cv2.imshow('sample',sample)
cv2.imshow('target',target)
roiHist=cv2.calcHist([roi_hsv],[0,1],None,[32,32],[0,180,0,256])
cv2.normalize(roiHist,roiHist,0,255,cv2.NORM_MINMAX)
dst=cv2.calcBackProject([target_hsv],[0,1],roiHist,[0,180,0,256],1)
cv2.imshow('backProjectionDemo',dst)
#2D 直方图
def hist2d_demo(image):
hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
hist=cv2.calcHist([image],[0,1,2],None,[8,8,8],[0,256,0,256,0,256])
cv2.imshow('hist2d',hist[1])
print(type(hist),hist.shape)
print(hist[:,:,0].shape)
plt.imshow(hist[:,:,0],interpolation='nearest')
plt.title('2D Histogram')
plt.show()
def hist3_2d_demo(image):
fig=plt.figure(figsize=(15,5))
ax=fig.add_subplot(131)
hist=cv2.calcHist([image],[0,1],None,[32,32],[0,256,0,256])
p=plt.imshow(hist,interpolation='nearest')
plt.colorbar(p)
ax=fig.add_subplot(132)
hist=cv2.calcHist([image],[1,2],None,[32,32],[0,256,0,256])
p=plt.imshow(hist,interpolation='nearest')
plt.colorbar(p)
ax=fig.add_subplot(133)
hist=cv2.calcHist([image],[0,2],None,[32,32],[0,256,0,256])
p=plt.imshow(hist,interpolation='nearest')
plt.colorbar(p)
print('2d Histogram shape:{}, with {} values'.format(hist.shape,hist.flatten().shape[0]))
hist=cv2.calcHist([image],[0,1,2],None,[8,8,8],[0,256,0,256,0,256])
print('3d Histogram shape:{}, with {} values'.format(hist.shape,hist.flatten().shape[0]))
plt.show()
if __name__ == '__main__':
src=cv2.imread('../opencv-python-img/lena.png')
#back_projection_demo()
#hist2d_demo(src)
hist3_2d_demo(src)
#plt.hist(src.ravel(),256,[0,256])
#plt.show()
cv2.waitKey(0)