此次导师给安排的任务是将下面两幅图像融合成一幅清晰的图像,根据图像可以看出第一幅图像左清晰右模糊,第二幅图像相反,通过图像融合将两幅图像融合为一幅左右都清晰的图像。
代码如下:
import numpy as np
import cv2 as cv
def fangcha(img):
row=img.shape[0]
col=img.shape[1]
varImg=np.zeros([row,col])
for i in range(row):#求取求方差范围
for j in range(col):
if i-5>0:
up=i-5
else:
up=0
if i+5<row:
down=i+5
else:
down=row
if j-5>0:
left=j-5
else:
left=0
if j+5<col:
right=j+5
else:
right=col
window=img[up:down,left:right]
mean,var=cv.meanStdDev(window)#调用OpenCV函数求取均值和方差
varImg[i,j]=var
return varImg
def qiuquan(img1,img2):
row=img1.shape[0]
col=img1.shape[1]
array1=fangcha(img1)#调用求方差函数
array2=fangcha(img2)
for i in range(row):#求权
for j in range(col):
weight1=array1[i,j]/(array1[i,j]+array2[i,j])
weight2=array2[i,j]/(array1[i,j]+array2[i,j])
array1[i,j]=weight1
array2[i,j]=weight2
return array1,array2
def ronghe(img1,img2):
cc = img1.copy()
b,g,r=cv.split(img1)#分通道处理
b1,g1,r1=cv.split(img2)
weight1,weight2=qiuquan(b,b1)#调用求权重函数
weight11,weight22=qiuquan(g,g1)
weight111,weight222=qiuquan(r,r1)
new_img=img1*1
row=new_img.shape[0]
col=new_img.shape[1]
b2,g2,r2 = cv.split(cc)
for i in range(row):#图像融合
for j in range(col):
b2[i,j]=(weight1[i,j]*b[i,j]+weight2[i,j]*b1[i,j]).astype(int)
g2[i,j]=(weight11[i,j]*g[i,j]+weight22[i,j]*g1[i,j]).astype(int)
r2[i,j]=(weight111[i,j]*r[i,j]+weight222[i,j]*r1[i,j]).astype(int)
new_img=cv.merge([b2,g2,r2])#通道合并
return new_img
img1=cv.imread("D:/s1.jpg")
img2=cv.imread("D:/s2.jpg")
img3=ronghe(img1,img2)
cv.imshow("img1",img1)
cv.imshow("img2",img2)
cv.imshow("img3",img3)
cv.waitKey(0)
cv.destroyAllWindows()
编写原理:
1 将两幅图片分通道处理;
2 分别取两幅图片的RGB图;
3 例如,将两幅图像的R通道图进行求权处理,然后将各个图像的权值乘像素点灰度值相加;
4 GB通道图同理。