3

我正在为 GIMP 开发一个 python 插件,我想获得一个层的 RGB 矩阵作为一个 numpy 数组。要访问 python 插件中的层,我使用下面的代码:

def python_function(img, layer):
    layer = img.layers[0]

我想创建layer一个变量,而不是 gimp.Image 变量,一个 numpy 数组,其中包含每个像素的 RGB 值。我在其他 nonGimp-python 代码中使用的是下一行:frame2 = misc.imread('C:\Users\User\Desktop\image2.png').astype(np.float32). 如果我打印frame2,我会得到一个这样的矩阵,其中包含每个像素的 RGB 值:

[[[ 111.  179.  245.]
  [ 111.  179.  245.]
  [ 111.  179.  245.]
  ..., 
  [  95.  162.  233.]
  [  95.  162.  233.]
  [  95.  162.  233.]]

 [[ 111.  179.  245.]
  [ 111.  179.  245.]
  [ 111.  179.  245.]
  ..., 
  [  95.  162.  233.]
  [  95.  162.  233.]
  [  95.  162.  233.]]

 [[ 111.  179.  245.]
  [ 111.  179.  245.]
  [ 111.  179.  245.]
  ..., 
  [  95.  162.  233.]
  [  95.  162.  233.]
  [  95.  162.  233.]]
  ..., 
  [ 113.  127.  123.]
  [ 113.  127.  123.]
  [ 113.  127.  123.]]

 [[  98.  112.  108.]
  [  98.  112.  108.]
  [  98.  112.  108.]
  ..., 
  [ 113.  127.  123.]
  [ 113.  127.  123.]
  [ 113.  127.  123.]]]

有什么方法可以将 gimp.Image 类型变量转换为 numpy 数组,而无需将其保存在文件中并使用 Scipy 重新加载它?

谢谢。

4

1 回答 1

5

你也看过“像素区域”。这些(很少)描述here。基本上,给定一个层:

您可以获得一个覆盖该层的区域,如下所示:

region=layer.get_pixel_rgn(0, 0, layer.width,layer.height)

您可以通过索引访问像素:

pixel=region[x,y]

这将返回一个 1/3/4 字节的字符串(参见 参考资料region.bpp),例如,一个白色像素作为'\xff\xff\xff' 返回,一个红色像素作为'\xff\x00\x00'(假设没有 alpha 通道:3bpp)。

您还可以使用切片访问区域,因此左上角的 4 个像素是:

cornerNW=region[0:2,0:2]

这将返回一个 12 个字节的字符串(16 个带有 alpha 通道)'\xff\x00\x00\xff\x00\x00\xff\x00\x00\xff\x00\x00'。这在另一个方向上起作用,您可以分配给一个区域:

region[0:2,0:2]='\xff'*12 # set to white

直接层<>nparray 函数

我在当前实验中使用的一对函数:

# Returns NP array (N,bpp) (single vector ot triplets)
def channelData(layer):
    region=layer.get_pixel_rgn(0, 0, layer.width,layer.height)
    pixChars=region[:,:] # Take whole layer
    bpp=region.bpp
    return np.frombuffer(pixChars,dtype=np.uint8).reshape(len(pixChars)/bpp,bpp)

def createResultLayer(image,name,result):
    rlBytes=np.uint8(result).tobytes();
    rl=gimp.Layer(image,name,image.width,image.height,image.active_layer.type,100,NORMAL_MODE)
    region=rl.get_pixel_rgn(0, 0, rl.width,rl.height,True)
    region[:,:]=rlBytes
    image.add_layer(rl,0)
    gimp.displays_flush()
于 2017-11-29T13:49:47.107 回答