python实现泊松图像融合


Posted in Python onJuly 26, 2018

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

```
from __future__ import division
import numpy as np 
import scipy.fftpack
import scipy.ndimage
import cv2
import matplotlib.pyplot as plt 
#sns.set(style="darkgrid")


def DST(x):
  """
  Converts Scipy's DST output to Matlab's DST (scaling).
  """
  X = scipy.fftpack.dst(x,type=1,axis=0)
  return X/2.0

def IDST(X):
  """
  Inverse DST. Python -> Matlab
  """
  n = X.shape[0]
  x = np.real(scipy.fftpack.idst(X,type=1,axis=0))
  return x/(n+1.0)

def get_grads(im):
  """
  return the x and y gradients.
  """
  [H,W] = im.shape
  Dx,Dy = np.zeros((H,W),'float32'), np.zeros((H,W),'float32')
  j,k = np.atleast_2d(np.arange(0,H-1)).T, np.arange(0,W-1)
  Dx[j,k] = im[j,k+1] - im[j,k]
  Dy[j,k] = im[j+1,k] - im[j,k]
  return Dx,Dy

def get_laplacian(Dx,Dy):
  """
  return the laplacian
  """
  [H,W] = Dx.shape
  Dxx, Dyy = np.zeros((H,W)), np.zeros((H,W))
  j,k = np.atleast_2d(np.arange(0,H-1)).T, np.arange(0,W-1)
  Dxx[j,k+1] = Dx[j,k+1] - Dx[j,k] 
  Dyy[j+1,k] = Dy[j+1,k] - Dy[j,k]
  return Dxx+Dyy

def poisson_solve(gx,gy,bnd):
  # convert to double:
  gx = gx.astype('float32')
  gy = gy.astype('float32')
  bnd = bnd.astype('float32')

  H,W = bnd.shape
  L = get_laplacian(gx,gy)

  # set the interior of the boundary-image to 0:
  bnd[1:-1,1:-1] = 0
  # get the boundary laplacian:
  L_bp = np.zeros_like(L)
  L_bp[1:-1,1:-1] = -4*bnd[1:-1,1:-1] \
           + bnd[1:-1,2:] + bnd[1:-1,0:-2] \
           + bnd[2:,1:-1] + bnd[0:-2,1:-1] # delta-x
  L = L - L_bp
  L = L[1:-1,1:-1]

  # compute the 2D DST:
  L_dst = DST(DST(L).T).T #first along columns, then along rows

  # normalize:
  [xx,yy] = np.meshgrid(np.arange(1,W-1),np.arange(1,H-1))
  D = (2*np.cos(np.pi*xx/(W-1))-2) + (2*np.cos(np.pi*yy/(H-1))-2)
  L_dst = L_dst/D

  img_interior = IDST(IDST(L_dst).T).T # inverse DST for rows and columns

  img = bnd.copy()

  img[1:-1,1:-1] = img_interior

  return img

def blit_images(im_top,im_back,scale_grad=1.0,mode='max'):
  """
  combine images using poission editing.
  IM_TOP and IM_BACK should be of the same size.
  """
  assert np.all(im_top.shape==im_back.shape)

  im_top = im_top.copy().astype('float32')
  im_back = im_back.copy().astype('float32')
  im_res = np.zeros_like(im_top)

  # frac of gradients which come from source:
  for ch in xrange(im_top.shape[2]):
    ims = im_top[:,:,ch]
    imd = im_back[:,:,ch]

    [gxs,gys] = get_grads(ims)
    [gxd,gyd] = get_grads(imd)

    gxs *= scale_grad
    gys *= scale_grad

    gxs_idx = gxs!=0
    gys_idx = gys!=0
    # mix the source and target gradients:
    if mode=='max':
      gx = gxs.copy()
      gxm = (np.abs(gxd))>np.abs(gxs)
      gx[gxm] = gxd[gxm]

      gy = gys.copy()
      gym = np.abs(gyd)>np.abs(gys)
      gy[gym] = gyd[gym]

      # get gradient mixture statistics:
      f_gx = np.sum((gx[gxs_idx]==gxs[gxs_idx]).flat) / (np.sum(gxs_idx.flat)+1e-6)
      f_gy = np.sum((gy[gys_idx]==gys[gys_idx]).flat) / (np.sum(gys_idx.flat)+1e-6)
      if min(f_gx, f_gy) <= 0.35:
        m = 'max'
        if scale_grad > 1:
          m = 'blend'
        return blit_images(im_top, im_back, scale_grad=1.5, mode=m)

    elif mode=='src':
      gx,gy = gxd.copy(), gyd.copy()
      gx[gxs_idx] = gxs[gxs_idx]
      gy[gys_idx] = gys[gys_idx]

    elif mode=='blend': # from recursive call:
      # just do an alpha blend
      gx = gxs+gxd
      gy = gys+gyd

    im_res[:,:,ch] = np.clip(poisson_solve(gx,gy,imd),0,255)

  return im_res.astype('uint8')


def contiguous_regions(mask):
  """
  return a list of (ind0, ind1) such that mask[ind0:ind1].all() is
  True and we cover all such regions
  """
  in_region = None
  boundaries = []
  for i, val in enumerate(mask):
    if in_region is None and val:
      in_region = i
    elif in_region is not None and not val:
      boundaries.append((in_region, i))
      in_region = None

  if in_region is not None:
    boundaries.append((in_region, i+1))
  return boundaries


if __name__=='__main__':
  """
  example usage:
  """
  import seaborn as sns

  im_src = cv2.imread('../f01006.jpg').astype('float32')

  im_dst = cv2.imread('../f01006-5.jpg').astype('float32')

  mu = np.mean(np.reshape(im_src,[im_src.shape[0]*im_src.shape[1],3]),axis=0)
  # print mu
  sz = (1920,1080)
  im_src = cv2.resize(im_src,sz)
  im_dst = cv2.resize(im_dst,sz)

  im0 = im_dst[:,:,0] > 100
  im_dst[im0,:] = im_src[im0,:]
  im_dst[~im0,:] = 50
  im_dst = cv2.GaussianBlur(im_dst,(5,5),5)

  im_alpha = 0.8*im_dst + 0.2*im_src

  # plt.imshow(im_dst)
  # plt.show()

  im_res = blit_images(im_src,im_dst)

  import scipy
  scipy.misc.imsave('orig.png',im_src[:,:,::-1].astype('uint8'))
  scipy.misc.imsave('alpha.png',im_alpha[:,:,::-1].astype('uint8'))
  scipy.misc.imsave('poisson.png',im_res[:,:,::-1].astype('uint8'))

  im_actual_L = cv2.cvtColor(im_src.astype('uint8'),cv2.cv.CV_BGR2Lab)[:,:,0]
  im_alpha_L = cv2.cvtColor(im_alpha.astype('uint8'),cv2.cv.CV_BGR2Lab)[:,:,0]
  im_poisson_L = cv2.cvtColor(im_res.astype('uint8'),cv2.cv.CV_BGR2Lab)[:,:,0]

  # plt.imshow(im_alpha_L)
  # plt.show()
  for i in xrange(500,im_alpha_L.shape[1],5):
    l_actual = im_actual_L[i,:]#-im_actual_L[i,:-1]
    l_alpha = im_alpha_L[i,:]#-im_alpha_L[i,:-1]
    l_poisson = im_poisson_L[i,:]#-im_poisson_L[i,:-1]


    with sns.axes_style("darkgrid"):
      plt.subplot(2,1,2)
      #plt.plot(l_alpha,label='alpha')

      plt.plot(l_poisson,label='poisson')
      plt.hold(True)
      plt.plot(l_actual,label='actual')
      plt.legend()

      # find "text regions":
      is_txt = ~im0[i,:]
      t_loc = contiguous_regions(is_txt)
      ax = plt.gca()
      for b0,b1 in t_loc:
        ax.axvspan(b0, b1, facecolor='red', alpha=0.1)

    with sns.axes_style("white"):
      plt.subplot(2,1,1)
      plt.imshow(im_alpha[:,:,::-1].astype('uint8'))
      plt.hold(True)
      plt.plot([0,im_alpha_L.shape[0]-1],[i,i],'r')
      plt.axis('image')
      plt.show()


  plt.subplot(1,3,1)
  plt.imshow(im_src[:,:,::-1].astype('uint8'))
  plt.subplot(1,3,2)
  plt.imshow(im_alpha[:,:,::-1].astype('uint8'))
  plt.subplot(1,3,3)  
  plt.imshow(im_res[:,:,::-1]) #cv2 reads in BGR
  plt.show()

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

Python 相关文章推荐
比较详细Python正则表达式操作指南(re使用)
Sep 06 Python
从零学Python之引用和类属性的初步理解
May 15 Python
Python数据分析之双色球中蓝红球分析统计示例
Feb 03 Python
分享一下Python数据分析常用的8款工具
Apr 29 Python
使用Python来开发微信功能
Jun 13 Python
pandas.DataFrame的pivot()和unstack()实现行转列
Jul 06 Python
PYTHON绘制雷达图代码实例
Oct 15 Python
Python实现元素等待代码实例
Nov 11 Python
Python 基于wxpy库实现微信添加好友功能(简洁)
Nov 29 Python
谈一谈数组拼接tf.concat()和np.concatenate()的区别
Feb 07 Python
Python实战实现爬取天气数据并完成可视化分析详解
Jun 16 Python
彻底弄懂Python中的回调函数(callback)
Jun 25 Python
python中的decorator的作用详解
Jul 26 #Python
python opencv实现旋转矩形框裁减功能
Jul 25 #Python
Python3匿名函数用法示例
Jul 25 #Python
Python实现动态添加属性和方法操作示例
Jul 25 #Python
利用pandas读取中文数据集的方法
Jul 25 #Python
利用pandas进行大文件计数处理的方法
Jul 25 #Python
使用python验证代理ip是否可用的实现方法
Jul 25 #Python
You might like
怎样去阅读一份php源代码
2009/08/21 PHP
php similar_text()函数的定义和用法
2016/05/12 PHP
php readfile()修改文件上传大小设置
2017/08/11 PHP
PHP基于openssl实现的非对称加密操作示例
2019/01/11 PHP
Jquery常用技巧收集整理篇
2010/11/14 Javascript
前后台交互过程中json格式如何解析以及如何生成
2012/12/26 Javascript
jQuery 遍历- 关于closest() 的方法介绍以及与parents()的方法区别分析
2013/04/26 Javascript
JavaScript利用正则表达式去除日期中的-
2014/06/09 Javascript
javascript中call,apply,bind的用法对比分析
2015/02/12 Javascript
AngularJS基础 ng-src 指令简单示例
2016/08/03 Javascript
js插件Jcrop自定义截取图片功能
2016/10/14 Javascript
javascript遍历json对象的key和任意js对象属性实例
2017/03/09 Javascript
Javascript实现一个简单的输入关键字添加标签效果实例
2017/06/01 Javascript
使用travis-ci如何持续部署node.js应用详解
2017/07/30 Javascript
说说AngularJS中的$parse和$eval的用法
2017/09/14 Javascript
微信小程序非swiper组件实现的自定义伪3D轮播图效果示例
2018/12/11 Javascript
微信小程序点击按钮动态切换input的disabled禁用/启用状态功能
2020/03/07 Javascript
python使用multiprocessing模块实现带回调函数的异步调用方法
2015/04/18 Python
python实现根据ip地址反向查找主机名称的方法
2015/04/29 Python
Python生成任意范围任意精度的随机数方法
2018/04/09 Python
python实现微信小程序自动回复
2018/09/10 Python
Python离线安装PIL 模块的方法
2019/01/08 Python
Python Numpy数组扩展repeat和tile使用实例解析
2019/12/09 Python
网页切图的CSS和布局经验与要点
2015/04/09 HTML / CSS
飞利浦比利时官方网站:Philips比利时
2016/08/24 全球购物
美国首屈一指的高品质珠宝设计师和零售商:Allurez
2018/01/23 全球购物
Yahoo的PHP面试题
2014/05/26 面试题
高二政治教学反思
2014/02/01 职场文书
任命书模板
2014/06/04 职场文书
村道德模范事迹材料
2014/08/28 职场文书
2015建军节87周年演讲稿
2015/03/19 职场文书
如何获取numpy array前N个最大值
2021/05/14 Python
Java基于字符界面的简易收银台
2021/06/26 Java/Android
关于python pygame游戏进行声音添加的技巧
2021/10/24 Python
警用民用对讲机找不同
2022/02/18 无线电
零基础学java之带参数以及返回值的方法
2022/04/10 Java/Android