2011-05-22 140 views
3

我现在正在使用numpy和scipy在python中进行图像处理。我有一段可以放大图像的代码,但不知道这是如何工作的。任何人都可以请解释这个python代码如何逐行工作?

所以请一些python/numpy的专家在python中逐行解释一下。我总是渴望学习。

import numpy as N 
import os.path 
import scipy.signal 
import scipy.interpolate 
import matplotlib.pyplot as plt 
import matplotlib.cm as cm 


def enlarge(img, rowscale, colscale, method='linear'): 
    x, y = N.meshgrid(N.arange(img.shape[1]), N.arange(img.shape[0])) 
    pts = N.column_stack((x.ravel(), y.ravel())) 
    xx, yy = N.mgrid[0.:float(img.shape[1]):1/float(colscale), 
      0.:float(img.shape[0]):1/float(rowscale)] 
    large = scipy.interpolate.griddata(pts, img.flatten(), (xx, yy), method).T 
    large[-1,:] = large[-2,:] 
    large[:,-1] = large[:,-2] 
    return large 

非常感谢。

+2

Python中每个语句的缩进都很重要。请修正您的代码片段的格式。 – Johnsyweb 2011-05-22 05:54:02

+0

感谢和抱歉。我添加了这些导入..以清除它 – 2011-05-22 06:03:50

+0

请注意,在这里使用'griddata'不是最有效的选项,因为网格总是矩形的。更有效的选项是:'scipy.interpolate.RectBivariateSpline'和'scipy.ndimage.zoom'。 – 2011-05-31 08:24:50

回答

4

首先,用每像素点数创建一个空点网格。

x, y = N.meshgrid(N.arange(img.shape[1]), N.arange(img.shape[0])) 

实际图像的像素被放置在可变pts这将在后面需要。

pts = N.column_stack((x.ravel(), y.ravel())) 

在此之后,它产生具有每个像素一个点用于放大图像的网格;如果原始图像是200x400,colscale设置为4,并且rowscale设置为2,则网格网格将具有(200 * 4)x(400 * 2)或800x800点。

xx, yy = N.mgrid[0.:float(img.shape[1]):1/float(colscale), 
     0.:float(img.shape[0]):1/float(rowscale)] 

使用scipy,将pts变量中的点插入到较大的网格中。插值是通常在从较小点集合到较大点集合时填充或估计缺失点的方式。

large = scipy.interpolate.griddata(pts, img.flatten(), (xx, yy), method).T 

我不是100%肯定是什么最后两行,而不必返回,并在看的GridData方法返回什么。它似乎正在抛出一些图像不需要或执行翻译的额外数据。

large[-1,:] = large[-2,:] 
large[:,-1] = large[:,-2] 
return large 
相关问题