[英]How to extract R,G,B values with numpy into seperate arrays
Suppose I have a image with some dimension (1920, 1080, 3)
, I want to extract out R,G,B values into separate arrays R , G, B
.假设我有一个尺寸为
(1920, 1080, 3)
,我想将 R,G,B 值提取到单独的数组R , G, B
。 I tried to do it like我试着这样做
for i in range(image.shape[0]):
for j in range(image.shape[1]):
B = np.append(B, image[i, j][0])
G = np.append(G, image[i, j][1])
R = np.append(R, image[i, j][2])
But as expected this is very slow , How can I do this with numpy in built function?但正如预期的那样,这很慢,我如何在内置函数中使用 numpy 来做到这一点?
If you want it to use in OpenCV
way then you may use cv2.split()
, keeping in mind channels of your image: 如果您希望以
OpenCV
方式使用它,那么您可以使用cv2.split()
,记住图像的通道:
b, g, r = cv2.split(image) # For BGR image
b, g, r, a = cv2.split(image) # for BGRA image
Or if you may like direct numpy format then you may use directly [which seems to be more efficient as per comments of @igaurav] 或者,如果您可能喜欢直接numpy格式,那么您可以直接使用[根据@igaurav的评论,这似乎更有效]
b, g, r = image[:, :, 0], image[:, :, 1], image[:, :, 2] # For RGB image
b, g, r, a = image[:, :, 0], image[:, :, 1], image[:, :, 2], image[:, :, 3] # for BGRA image
You may use np.shape[2]
to check the number of channels in the given image. 您可以使用
np.shape[2]
来检查给定图像中的通道数。
dsplit
it. dsplit
它。
import numpy as np
def channelSplit(image):
return np.dsplit(image,image.shape[-1])
[B,G,R]=channelSplit(image)
This works for RGB or RGBA images. 这适用于RGB或RGBA图像。
This works for me:这对我有用:
def split_channels(im: np.ndarray):
assert len(im.shape) == 3 and im.shape[-1] == 3
return np.squeeze(np.split(im, im.shape[-1], -1), axis=-1)
Note that, the np.split
itself is not enough, which will leave you a (M, N, 1)
image.请注意,
np.split
本身是不够的,它会给你留下一个(M, N, 1)
图像。 But if you want to have (M, N)
, then the squeeze
works.但是如果你想要
(M, N)
,那么squeeze
可以了。
You can remove the assert
if you have other cases.如果您有其他情况,您可以删除
assert
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.