使用numpy将数据从一个通道交换到另一个通道

时间:2019-03-01 20:16:37

标签: python numpy

我一直在研究如何将通道从BGR更改为RGB,然后就出现了。这有效,但是我对这种语法感到困惑。这种数据交换在numpy中到底如何工作?

来自gist的代码:

rgb = bgr[...,::-1]

2 个答案:

答案 0 :(得分:3)

...只是一个占位符,可以避免语法错误,而::-1的意思是沿最后一个维度反转数组的元素。

例如:

In [4]: rgb = np.arange(12).reshape(2,2,3)

In [5]: rgb
Out[5]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])
In [8]: rgb[...,::-1]
Out[8]: 
array([[[ 2,  1,  0],
        [ 5,  4,  3]],

       [[ 8,  7,  6],
        [11, 10,  9]]])

答案 1 :(得分:2)

我不是Numpy及其操作的专家,但是我可以向您展示如何使用各种切片(索引?)技术进行某些图像处理。

通常,在RGB图像上,操作用逗号分隔,如下所示:

newImage = oldImage[ROWSTUFF, COLUMNSTUFF, CHANNELSTUFF]

ROWSTUFF,COLUMNSTUFF和CHANNELSTUFF分别由以下组成:

start:end:step

因此,让我们对该图像进行一些处理:

enter image description here

# Load image with PIL/Pillow and make Numpy array - you can equally use OpenCV imread(), or other libraries
im = np.array(Image.open('start.png').convert('RGB'))                                           

# im.shape is (400, 400, 3)

# Now extract top half by ending ROWSTUFF at 200
tophalf = im[:200,:,:]

enter image description here


# Now extract bottom half by starting ROWSTUFF at 200
bottomhalf = im[200:,:,:] 

enter image description here


# Now extract left half by ending ROWSTUFF at 200
lefthalf = im[:,:200,:]

enter image description here


# Now extract right half by starting ROWSTUFF at 200
righthalf = im[:,200:,:]  

enter image description here


# Now scale the image by taking only every 4th row and every second column:
scaled = im[::4,::2,:]

enter image description here


# Now extract Red channel, by setting CHANNELSTUFF to 0
red = im[:,:,0]

enter image description here


# Now extract Green channel, by setting CHANNELSTUFF to 1
green = im[:,:,1] 

enter image description here


# Now flop the image top to bottom by striding backwards through ROWSTUFF
flop = im[::-1,:,:]

enter image description here


# Now flip the image left to right by striding backwards through COLUMNSTUFF
flip = im[:,::-1,:]  

enter image description here


# And finally, like the question, reverse the channels by striding through CHANNELSTUFF backwards, which will make RGB -> BGR, thereby leaving Green and black unchanged
OP = im[:,:,::-1]  

enter image description here


然后意识到...“保留未指定尺寸的原样”的缩写形式,所以

[:,:,:,:, a:b:c] can be written as [..., a:b:c]

[a:b:c, :,:,:,:,:] can be written as [a:b:c, ...]

关键字:图像处理,处理,图像,Python,Numpy,翻转,翻牌,反向,步幅,开始,结束,范围,切片,切片,提取,缩放,通道,反向,BGR到RGB,RGB到BGR。