Skip to main content
 首页 » 编程设计

python之使用 numpy 将数据从一个 channel 交换到另一个 channel

2025年05月04日21freeliver54

我正在研究如何将 channel 从 BGR 更改为 RGB,然后想到了这个。这行得通,但我对这种语法感到困惑。这种类型的数据交换在 numpy 中究竟是如何工作的?

代码来自 gist :

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

请您参考如下方法:

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

一般而言,在 RGB 图像上,操作以逗号分隔,如下所示:

newImage = oldImage[ROWSTUFF, COLUMNSTUFF, CHANNELSTUFF] 

其中 ROWSTUFF、COLUMNSTUFF 和 CHANNELSTUFF 分别由以下部分组成:

start:end:step 

那么,让我们对这张图片做一些处理:

# 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,:,:] 


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


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


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


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


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


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


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


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


# 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]   


然后只需意识到 ... 是“保留未指定的尺寸原样” 的简写,所以

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

和

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

关键字:图像处理、过程、图像、Python、Numpy、翻转、翻转、反转、跨步、开始、结束、范围、切片、切片、提取、缩放、 channel 、反转、BGR到 RGB,RGB 到 BGR。