首页 > 编程 > Python > 正文

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

2020-02-15 23:54:28
字体:
来源:转载
供稿:网友

根据导师作业安排,在学习数字图像处理(刚萨雷斯版)第六章 彩色图像处理 中的彩色模型后,导师安排了一个比较有趣的作业:

融合原理为:

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

2 步骤:(1)将RGB转换为HSV空间(H:色调,S:饱和度,V:明度);

(2)用Gray图像诶换掉HSV中的V;

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

书上只介绍了HSI彩色模型,并没有说到HSV,所以需要网上查找资料。

Python代码如下:

import cv2import numpy as npimport mathfrom matplotlib import pyplot as pltdef 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=img1weight=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.shapeH=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]=MAXif V[i,j]0:S[i,j]=0else: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)+120elif V[i,j]==b[i,j]:H[i,j]=60*(float(r[i,j])-g[i,j])/(V[i,j]-MIN)+240if H[i,j]<0:H[i,j]=H[i,j]+360H[i,j]=H[i,j]/2S[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.shapefor 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 newimgdef HSVtoRGB(img,rgb):h1,s1,v1=cv2.split(img)rg = rgb.copy()rows,cols=h1.shaper,g,b=0.0,0.0,0.0b1,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]/255s=s1[i][j]/255h=h2hx=int(h/60.0)hi=hx%6f=hx-hip=v(1-s)q=v*(1-fs)t=v(1-(1-f)s)if hi0:r,g,b=v,t,pelif hi1:r,g,b=q,v,pelif hi2:r,g,b=p,v,telif hi3:r,g,b=p,q,velif hi4:r,g,b=t,p,velif hi5:r,g,b=v,p,qr,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 rgimg=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)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()            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表