如何有效地填充RGB像素,使其成为使用numpy的结果图像的中心像素

时间:2014-05-21 22:13:33

标签: python numpy

我的图像由100个像素组成。对于每个像素,我想用零填充它(如果在边缘上),使其位于中心,与相邻像素连接并生成新的10x10图像。因此,我希望通过沿着行滑动每个像素来从原始图像生成100个图像。例如对于像素[0,0],我想在右边添加4个零列,在顶部添加4个零行,在右边添加相邻的5个列像素,在底部添加相邻的5个行像素。

有人可以指导我如何使用numpy对RGB图像进行此操作吗?

def unpickle_im(file, type):
import Image
im1 = Image.open(file)
im1p = np.asarray(im1, dtype=type)
return im1p

imc2p = unpickle_im('tmp/RGB-00000.png', 'float32')
##imc2p.shape = (10,10,3)

padded = np.zeros(10,10,3) ##Create a padded image filled with zeros
for i in xrange(im2cp.shape[0]):
for j in xrange(im2cp.shape[1]):
    if(i < 5  or j < 5) :
        new_im2cp = np.pad(im2cp[i:5, j:5], ((4-i,4-j),(0,0)))
    else:
        new_im2cp = np.pad(im2cp[i-4:i+5, j-4:j+5])

编辑:在@dabhaid的帖子后添加正确的片段:

from PIL import Image
import numpy as np, time

im_array = np.random.rand(10,10,3)
pad = 4
padded_array  = np.pad(im_array, ((pad,pad+1),(pad,pad+1),(0,0)), 'constant')
for i in xrange(im_array.shape[0]):
    for j in xrange(im_array.shape[1] ):
       temp_im = padded_array[i:i+10, j:j+10]
       # print temp_im.shape
       if i == 0 and j == 0:
        new_im = temp_im[np.newaxis,...]
       else:
        new_im = np.vstack([new_im, temp_im[np.newaxis,...]])

2 个答案:

答案 0 :(得分:1)

我假设你有一个RGB图像(而不是RGBA)。根据评论,这是你想要的吗?

from PIL import Image
import numpy as np

image = Image.open('100.png')
im_array = np.array(image)
stack = np.array(100, 20, 20, 3) #100 of the padded arrays

for i in xrange(im_array.shape[0]):
    for j in xrange(im_array.shape[1]):
        padded = np.zeros((20,20,3))
        padded[9][9] = im_array[i][j]
        stack[i*j] = padded

看起来很浪费,记忆力很强。

编辑以回答问题更新

而不是有条件地填充新图像,填充原始图像,然后只复制子图像:

from PIL import Image
import numpy as np

image = Image.open('100.png')
im_array = np.array(image)
pad = 4 #pixels
padded_array = np.pad(im_array, ((pad,pad+1),(pad,pad+1),(0,0)), 'constant')
# pad 4 elements to the left, right, up and down, but leave the pixel values alone
# default value is zero
for i in xrange(im_array.shape[0] - (pad + pad+1)):
    for j in xrange(im_array.shape[0] - (pad + pad+1)):
        new_imarray = padded_array[i:i+9, j:j+9]
        # do what you need with the new image

答案 1 :(得分:0)

from PIL import Image
import numpy as np, time

im_array = np.random.rand(10,10,3)
pad = 4
padded_array  = np.pad(im_array, ((pad,pad+1),(pad,pad+1),(0,0)), 'constant')
for i in xrange(im_array.shape[0]):
    for j in xrange(im_array.shape[1] ):
       temp_im = padded_array[i:i+10, j:j+10]
       # print temp_im.shape
       if i == 0 and j == 0:
        new_im = temp_im[np.newaxis,...]
       else:
        new_im = np.vstack([new_im, temp_im[np.newaxis,...]])