[英]Gimp Python plugin gimp.Image as numpy array
我正在為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重新加載?
謝謝。
你也看過“像素區域”。 這些(略有不同) 在這里描述。 基本上,給定一層:
您可以獲得覆蓋圖層的區域,如下所示:
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
我在當前實驗中使用的一對函數:
# 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.