根据导师作业安排,在学习数字图像处理(刚萨雷斯版)第六章 彩色图像处理 中的彩色模型后,导师安排了一个比较有趣的作业:
如图有遥感原RGB图image,灰色图像Grayimage,将两幅图合并为第三幅清晰的遥感RGB图像RGBimage
融合原理为:
1 注意:遥感原RGB图image和灰色图Grayimage为测试用的输入图像;
2 步骤:(1)将RGB转换为HSV空间(H:色调,S:饱和度,V:明度);
(2)用灰色图转换成的灰度图Gray图像替换掉HSV中的V;
(3)替换后的HSV转换回RGB空间即可得到结果。
书上只介绍了HSI彩色模型,并没有说到HSV,所以需要网上查找资料。
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=img*1
weight=img.shape[0]
height=img.shape[1]
for i in range(weight):
for j in range(height):
grayimg[i,j]=0.299*img[i,j,0]+0.587*img[i,j,1]+0.114*img[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 MAX==MIN:
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):#将灰度图替换HSV中的V
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=h*2
hx=int(h/60.0)
hi=hx%6
f=hx-hi
p=v*(1-s)
q=v*(1-f*s)
t=v*(1-(1-f)*s)
if hi==0:
r,g,b=v,t,p
elif hi==1:
r,g,b=q,v,p
elif hi==2:
r,g,b=p,v,t
elif hi==3:
r,g,b=p,q,v
elif hi==4:
r,g,b=t,p,v
elif hi==5:
r,g,b=v,p,q
r,g,b=(r*255),(g*255),(b*255)
r1[i][j]=int(r)
g1[i][j]=int(g)
b1[i][j]=int(b)
rg=cv2.merge([b1,g1,r1])
return rg
img=cv2.imread("D:/RGB.bmp")
gray=cv2.imread("D:/gray.bmp")
img=caijian(img)
gray=caijian(gray)
grayimg=graytograyimg(gray)
HSVimg=RGBtoHSV(img)
HSgray=graytoHSgry(grayimg,HSVimg)
RGBimg=HSVtoRGB(HSgray,img)
#RGBimg=HSVtoRGB1(HSgray)
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()
以上代码是在尽量不调用OpenCV函数的情况下编写,其目的是熟悉图像处理原理和Python编程,注释很少,其中RGB转HSV原理,HSV转RGB原理,在CSDN中都能找到,灰度图替换HSV中的V原理其实很简单,看代码就能明白,不用再找资料。
此次小有收获,分享给各位,纯属写着玩。