2011-05-22 78 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 
相關問題