python - Gimp Python 插件 gimp.Image 作为 numpy 数组

标签 python numpy plugins gimp gimpfu

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

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

我想制作 layer 变量,而不是 gimp.Image 变量,一个包含每个像素的 RGB 值的 numpy 数组。我在其他非 Gimp-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 重新加载它?

谢谢。

最佳答案

您太看重“像素区域”了。这些(略微)描述了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 channel :3bpp)。

你也可以访问带有切片的区域,所以左上角的 4 个像素是:

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

这将返回一个 12 字节的字符串(16 个带有 alpha channel )'\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()

关于python - Gimp Python 插件 gimp.Image 作为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47536186/

相关文章:

python - 使用 Pandas 数据框查找不同小数位的值

apache - org.jibx : maven-jibx-plugin:1. 2.1 - 读取路径错误

plugins - Eclipse RCP : Add required plugins automatically to feature

python - json_utils.dumps 突然从 flask 中返回所有 unicode

python - 如何让 grabCut 与 GC_INIT_WITH_MASK 一起工作 opencv python

python - "Adding"Tesseract eng.traineddata 的新字体

python - Pandas 使用跨多个列的字典值相乘

Android Studio 4.1 插件错误 : Plugin * is incompatible (supported only in IntelliJ IDEA)

python - Vim 表格 : how to ignore long comments

python - 标签颜色更改其他标签