开发者

Can anyone please explain how this python code works line by line?

I am working in image processing right now in python using numpy and scipy all the time. I have one piece of code that can enlarge an开发者_如何学JAVA image, but not sure how this works.

So please some expert in scipy/numpy in python can explain to me line by line. I am always eager to learn.

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

Thanks a lot.


First, a grid of empty points is created with point per pixel.

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

The actual image pixels are placed into the variable pts which will be needed later.

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

After that, it creates a mesh grid with one point per pixel for the enlarged image; if the original image was 200x400, the colscale set to 4 and rowscale set to 2, the mesh grid would have (200*4)x(400*2) or 800x800 points.

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

Using scipy, the points in pts variable are interpolated into the larger grid. Interpolation is the manner in which missing points are filled or estimated usually when going from a smaller set of points to a larger set of points.

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

I am not 100% certain what the last two lines do without going back and looking at what the griddata method returns. It appears to be throwing out some additional data that isn't needed for the image or performing a translation.

large[-1,:] = large[-2,:]
large[:,-1] = large[:,-2]
return large
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜