使用skimage库调整图像大小而不拉伸

时间:2015-02-14 02:42:30

标签: python image numpy

嘿,我正在尝试调整图像大小而不拉伸它,而是添加白色像素。我看起来很好,但我没有发现任何具体说明如何从skimage中实现。所以我使用numpy在调整大小之前添加额外的像素作为[float(255)]的数组。

from skimage.io import imread
from skimage.io import imsave
from skimage.transform import resize
from matplotlib import pyplot as plt
from pylab import cm
import numpy as np
from skimage import morphology
from skimage import measure
from scipy import misc
def process(file_):
    im = imread(file_, as_grey=True)
    #im = misc.imread(file_)
    #im=np.fromfile(file_, dtype=np.int64)

    #Filler to avoid stretching
    orig_rows, orig_cols = im.shape
    print orig_rows, orig_cols
    if orig_rows < orig_cols:
        for addition in range(0,orig_cols-orig_rows):
            #adding white rows
            lst = np.array(list(float(255) for x in range(0,orig_cols)))
            im= np.vstack((im,lst))
    if orig_rows > orig_cols:
        for addition in range(0,orig_rows-orig_cols):
            #adding white columns
            lst = np.array(list([float(255)] for x in range(0,orig_rows)))
            im= np.hstack((im,lst))
    image = resize(im, (48, 48))
    imsave('test.jpg',im)
    imsave('test1.jpg',image)
    plt.imshow(im, cmap=cm.gray)
    plt.show()

当我用pyplot查看图像时,它看起来像这样 Image after numpy concatenations original 我们可以看到已经添加了列,但是在用

保存图像之后
image = resize(im, (48, 48))
    imsave('test.jpg',im)
    imsave('test1.jpg',image)

图像看起来像负片,调整后的图像看起来完全是白色的(在黑暗旁边,在网站背景上看不到它)。有什么想法吗?

Saved image Resized and saved image

1 个答案:

答案 0 :(得分:0)

以下代码应该有效。请注意,填充区域的颜色不完全是白色,以便查看上载图像中的图像边界。对于白色填充集fill_cval = np.max(img)

def resize_padded(img, new_shape, fill_cval=None, order=1):
    import numpy as np
    from skimage.transform import resize
    if fill_cval is None:
        fill_cval = np.max(img)
    ratio = np.min([n / i for n, i in zip(new_shape, img.shape)])
    interm_shape = np.rint([s * ratio for s in img.shape]).astype(np.int)
    interm_img = resize(img, interm_shape, order=order, cval=fill_cval)

    new_img = np.empty(new_shape, dtype=interm_img.dtype)
    new_img.fill(fill_cval)

    pad = [(n - s) >> 1 for n, s in zip(new_shape, interm_shape)]
    new_img[[slice(p, -p, None) if 0 != p else slice(None, None, None) 
             for p in pad]] = interm_img

    return new_img

import numpy as np
import matplotlib.pylab as plt
from skimage.data import astronaut
from skimage.color import rgb2gray  # using luminance
from skimage.io import imsave
img = rgb2gray(astronaut())

# set desired image size
out_size = (30, 100)  # height, width

# set the color of the padded area. Here: "95% luminance"
fill_cval = np.max(img) * 0.95

resized_img = resize_padded(img, out_size, fill_cval=fill_cval)

imsave('img.png', img)
imsave('img_res.png', resized_img)

enter image description here