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

2024-09-30 16:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张100像素的图像。对于每个像素,我想用零填充(如果在边缘),使其位于中心,与相邻像素连接并生成新的10x10图像。因此,我想从原始图像生成100个图像,方法是沿着行滑动每个像素。e、 g.对于像素[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的帖子后添加正确的片段:

^{pr2}$

Tags: 图像imagetypenprgb像素fileshape
2条回答

我假设你有一个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

这似乎是浪费,记忆明智。在

编辑以回答问题更新

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

^{pr2}$
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,...]])

相关问题 更多 >