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)

4、模板匹配

#--------------------------模板匹配-------------------------

#模板匹配就是在整个图像区域发现与给定子图像匹配的小块区域
#所以模板匹配首先需要一个模板图像T(给定的子图像)
#另外需要一个待检测的图像----源图像
#工作方法,在待检测图像上,从左到右,从上向下计算模板图像与重叠子图像的匹配度,匹配程度越大,两者相同的可能性越大。


# 匹配方法:
# 差值平方和匹配:CV_TM_SQDIFF
# 标准化差值平方和匹配:CV_TM_SQDIFF_NORMED
# 相关匹配:CV_TM_CCORR
# 标准相关匹配:CV_TM_CCORR_NORMED
# 相关匹配:CV_TM_CCOEFF
# 标准相关匹配:CV_TM_CCOEFF_NORMED


import cv2
import numpy as np


def template_demo():
	tpl=cv2.imread('../opencv-python-img/roi.jpg')
	target=cv2.imread('../opencv-python-img/target.jpg')
	methods=[cv2.TM_SQDIFF_NORMED,cv2.TM_CCORR_NORMED,cv2.TM_CCOEFF_NORMED]
	th,tw=tpl.shape[:2]
	print(methods)
	for md in methods:
		print(methods)
		print('md',md)
		result=cv2.matchTemplate(target,tpl,md)
		min_val,max_val,min_loc,max_loc=cv2.minMaxLoc(result)
		if md==cv2.TM_SQDIFF_NORMED:
			tl=min_loc
		else:
			tl=max_loc
		br=(tl[0]+tw,tl[1]+th)
		cv2.rectangle(target,tl,br,(0,0,255),2)
		#cv2.imshow('match-'+np.str(md),result)
		cv2.imshow('match-'+np.str(md),target)



if __name__ == '__main__':
	template_demo()

	cv2.waitKey(0)

你可能感兴趣的:(opencv,opencv,python,图像处理)