# Python+OpenCV实现图像融合的原理及代码

1 注意：遥感原RGB图image和灰度图Grayimage为测试用的输入图像；

2 步骤：（1）将RGB转换为HSV空间（H：色调，S：饱和度，V：明度）；

（2）用Gray图像诶换掉HSV中的V；

（3）替换后的HSV转换回RGB空间即可得到结果。

Python代码如下：

```import cv2
import numpy as np
import math
from matplotlib import pyplot as plt
def caijian(img):#裁剪图像与否根据选择图像大小而定，调用了OpenCV函数
weight=img.shape[0]
height=img.shape[1]
print(“图像大小为：%d*%d”%(weight,height))
img=cv2.resize(img,(int(weight/2),int(height/2)),interpolation=cv2.INTER_CUBIC)
return(img)
def graytograyimg(img):
grayimg=img1
weight=img.shape[0]
height=img.shape[1]
for i in range(weight):
for j in range(height):
grayimg[i,j]=0.299img[i,j,0]+0.587img[i,j,1]+0.114img[i,j,2]
return(grayimg)
def RGBtoHSV(img):
b,g,r=cv2.split(img)
rows,cols=b.shape
H=np.ones([rows,cols],“float”)
S=np.ones([rows,cols],“float”)
V=np.ones([rows,cols],“float”)
print(“RGB图像大小：%d*%d”%(rows,cols))
for i in range(0, rows):
for j in range(0, cols):
MAX=max((b[i,j],g[i,j],r[i,j]))
MIN=min((b[i,j],g[i,j],r[i,j]))
V[i,j]=MAX
if V[i,j]0:
S[i,j]=0
else:
S[i,j]=(V[i,j]-MIN)/V[i,j]
if MAXMIN:
H[i,j]=0 # 如果rgb三向量相同，色调为黑
elif V[i,j]==r[i,j]:
H[i,j]=(60*(float(g[i,j])-b[i,j])/(V[i,j]-MIN))
elif V[i,j]==g[i,j]:
H[i,j]=60*(float(b[i,j])-r[i,j])/(V[i,j]-MIN)+120
elif V[i,j]==b[i,j]:
H[i,j]=60*(float(r[i,j])-g[i,j])/(V[i,j]-MIN)+240
if H[i,j]<0:
H[i,j]=H[i,j]+360
H[i,j]=H[i,j]/2
S[i,j]=255*S[i,j]
result=cv2.merge((H,S,V)) # cv2.merge函数是合并单通道成多通道
result=np.uint8(result)
return(result)
def graytoHSgry(grayimg,HSVimg):
H,S,V=cv2.split(HSVimg)
rows,cols=V.shape
for i in range(rows):
for j in range(cols):
V[i,j]=grayimg[i][j][0]
newimg=cv2.merge([H,S,V])
newimg=np.uint8(newimg)
return newimg
def HSVtoRGB(img,rgb):
h1,s1,v1=cv2.split(img)
rg = rgb.copy()
rows,cols=h1.shape
r,g,b=0.0,0.0,0.0
b1,g1,r1 = cv2.split(rg)
print(“HSV图像大小为：%d*%d”%(rows,cols))
for i in range(rows):
for j in range(cols):
h=h1[i][j]
v=v1[i][j]/255
s=s1[i][j]/255
h=h2
hx=int(h/60.0)
hi=hx%6
f=hx-hi
p=v(1-s)
q=v*(1-fs)
t=v(1-(1-f)s)
if hi0:
r,g,b=v,t,p
elif hi1:
r,g,b=q,v,p
elif hi2:
r,g,b=p,v,t
elif hi3:
r,g,b=p,q,v
elif hi4:
r,g,b=t,p,v
elif hi5:
r,g,b=v,p,q
r,g,b=(r255),(g255),(b255)
r1[i][j]=int®
g1[i][j]=int(g)
b1[i][j]=int(b)
rg=cv2.merge([b1,g1,r1])
return rg
img=caijian(img)
gray=caijian(gray)
grayimg=graytograyimg(gray)
HSVimg=RGBtoHSV(img)
HSgray=graytoHSgry(grayimg,HSVimg)
RGBimg=HSVtoRGB(HSgray,img)
cv2.imshow(“image”,img)
cv2.imshow(“Grayimage”,grayimg)
cv2.imshow(“HSVimage”,HSVimg)
cv2.imshow(“HSGrayimage”,HSgray)
cv2.imshow(“RGBimage”,RGBimg)
cv2.waitKey(0)
cv2.destroyAllWindows()```