欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现两张图片的像素融合

程序员文章站 2024-01-07 09:51:10
本文实例为大家分享了python实现两张图片像素融合的具体代码,供大家参考,具体内容如下 通过计算两张图片的颜色直方图特征,利用直方图对图片的颜色进行融合。...

本文实例为大家分享了python实现两张图片像素融合的具体代码,供大家参考,具体内容如下

通过计算两张图片的颜色直方图特征,利用直方图对图片的颜色进行融合。

import numpy as np
import cv2
from pil import image,exiftags
 
def calcmeanandvariance(img):
 row=img.shape[0]
 col=img.shape[1]
 #channel=img.shape[2]
 total=row*col
 print (row,col,total)
 mean=np.zeros((3))
 variance=np.zeros((3))
 sum=np.zeros((3))
 
 for i in range(row):
  for j in range(col):
   sum[0]+=img[i][j][0]
   sum[1]+=img[i][j][1]
   sum[2]+=img[i][j][2]
 
 mean[0]=sum[0]/total
 mean[1]=sum[1]/total
 mean[2]=sum[2]/total
 sum=np.zeros((3))
 for i in range(row):
  for j in range(col):
   sum[0]=np.square(img[i][j][0]-mean[0])
   sum[1]=np.square(img[i][j][1]-mean[1])
   sum[2]=np.square(img[i][j][2]-mean[2])
 
 variance[0]=np.sqrt(sum[0]/total)
 variance[1]=np.sqrt(sum[1]/total)
 variance[2]=np.sqrt(sum[2]/total)
 print (mean,variance)
 return mean,variance
 
def cololtransit(img1,img2):
 image1 = cv2.cvtcolor(img1, cv2.color_bgr2lab)
 image2=cv2.cvtcolor(img2, cv2.color_bgr2lab)
 mean1,variance1=calcmeanandvariance(image1)
 mean2,variance2=calcmeanandvariance(image2)
 #print (mean1,variance1)
 radio=np.zeros((3))
 
 radio[0]=variance2[0]/variance1[0]
 radio[1]=variance2[1]/variance1[1]
 radio[2]=variance2[2]/variance1[2]
 
 print('test', radio)
 
 row=image1.shape[0]
 col=image1.shape[1]
 for i in range(row):
  for j in range(col):
   image1[i][j][0]=min(255,max(0,radio[0]*(image1[i][j][0]-mean1[0])+mean2[0]))
   image1[i][j][1]=min(255,max(0,radio[1]*(image1[i][j][1]-mean1[1])+mean2[1]))
   image1[i][j][2]=min(255,max(0,radio[2]*(image1[i][j][2]-mean1[2])+mean2[2]))
 image = cv2.cvtcolor(image1, cv2.color_bgr2lab)
 return image
 
if __name__=='__main__':
 img1=cv2.imread('1.jpg')
 img2=cv2.imread('2.jpg')
 cv2.namedwindow('src')
 cv2.namedwindow('dst')
 #cv2.resizewindow('src',500,500)
 #cv2.resizewindow('dst',500,500)
 cv2.imshow('src',img1)
 cv2.imshow('dst',img2)
 cv2.waitkey()
 cv2.destroyallwindows()
 
 img=cololtransit(img1,img2)
 cv2.namedwindow('result')
 cv2.imshow('result',img)
 cv2.waitkey()
 cv2.destroyallwindows()
 #print (img)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。