python-opencv 图像处理基础 (五)颜色直方图+直方图均衡化+直方图比较+直方图反向投影

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)

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)

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)

猜你喜欢

转载自blog.csdn.net/zml194849/article/details/123394751