簡體   English   中英

在python中切割一個三維的ndarray

[英]Slicing a 3-Dimensional ndarray in python

我正在嘗試切片表示彩色圖像的ndarray的3-D實例,其中2-D數組中的每個元素(或像素)包含分別對應於紅色,綠色和藍色值的3個字節的數組。 我想分別為每種顏色切出2-D ndarray,這樣我就可以根據我們的實現要求對它們進行壓平並將它們端到端地連接起來。 我目前正在嘗試的代碼是......

red = image[:, :, 0]
green = image[:, :, 1]
blue = image[:, :, 2]
collapsed_image = numpy.concatenate((red.flatten('C'), green.flatten('C'), blue.flatten('C')), axis=0)

其中image是我的numpy.ndarray對象,包含3-D字節數組。 這是否能夠切割出每個顏色的二維陣列並將它們端對端壓平/連接在一起?

你的意思是要實現這樣的輸出嗎?

from scipy.ndimage import *
import matplotlib.pyplot as p
%matplotlib inline

im=imread('rgb.png')
print np.shape(im)

p.subplot(121)
p.imshow(im)

red = im[:, :, 0]
green = im[:, :, 1]
blue = im[:, :, 2]
imchannels = np.concatenate((red, green, blue))

p.subplot(122)
p.imshow(imchannels)

輸出:

(215L, 235L, 3L)

在此輸入圖像描述

ndarray已經是內存字節的扁平集合,但並不總是按所需順序排列。 np.rollaxis可以修改它。

舉個簡單的例子:

首先是經典的2x2圖像(每個數字與運河相關聯):

image=np.arange(12).reshape(2,2,3)%3

In [08]: image
Out[08]: 
array([[[0, 1, 2],
        [0, 1, 2]],

       [[0, 1, 2],
        [0, 1, 2]]], dtype=int32)

另一種觀點,運河第一:

bycolor= r,g,b = np.rollaxis(image,axis=2)

In [10]: bycolor
Out[10]: 
array([[[0, 0],
        [0, 0]],

       [[1, 1],
        [1, 1]],

       [[2, 2],
        [2, 2]]], dtype=int32)

和扁平的布局:

In [11]: image.flatten()
Out[11]: array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2], dtype=int32)

In [12]: bycolor.flatten()
Out[12]: array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int32)

我認為最后一個是你想要的: np.rollaxis(image,2).flatten()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM