根据条件将特定轴替换为其他值

问题描述 投票:0回答:3

假设我有original_image:作为(451, 521, 3)形状。 它在某些位置包含[0,0,0] RGB值。

我想用[0,0,0]替换所有[0,255,0]

我试过的是 我创建了具有True的面具,其中[0,0,0]位于original_image 那面具有(451, 521)形状

我以为我可以使用以下 new_original_image=original_image[mask] 但事实证明new_original_image只是一个数组(形状像(18,3))其所有元素(例如,[[ 97 68 108],[127 99 139],[156 130 170],...])都被maskoriginal_image数组的True过滤掉了

python numpy
3个回答
1
投票

这是一种方式

idx=np.all(np.vstack(a)==np.array([0,0,5]),1)
a1=np.vstack(a)
a1[idx]=[0,0,0]
yourary=a1.reshape(2,-1,3)
Out[150]: 
array([[[0, 0, 0],
        [0, 0, 1],
        [0, 0, 0],
        [0, 0, 0]],
       [[0, 0, 0],
        [0, 0, 1],
        [0, 0, 0],
        [0, 0, 0]]])

数据输入

a
Out[133]: 
array([[[0, 0, 0],
        [0, 0, 1],
        [0, 0, 5],
        [0, 0, 5]],
       [[0, 0, 0],
        [0, 0, 1],
        [0, 0, 5],
        [0, 0, 5]]])

1
投票

我想用[0,255,0]替换所有[0,0,0]

import cv2

img = cv2.imread("test.jpg")
rows, cols, channels = img.shape

for r in range(rows):
    for c in range(cols):
        if np.all(img[r,c][0]==[0,0,0]):
            img[r,c]=[0,255,0]

0
投票

根据Wen-Ben的回复解决方案,我尝试编写我想要实现的详细代码片段

# original_image which contains [0,0,0] at several location 
# in 2 (last) axis from (451, 521, 3) shape image
# Stack original_image or using original_image.reshape((-1,3)) is also working
stacked=np.vstack(original_image)
# print(stacked.shape)
# (234971, 3)

# Create mask array which has True where [0,0,0] are located in stacked array
idx=np.all(stacked==[0,0,0],1)
# print(idxs.shape)
# (234971,)

# Replace existing values which are filtered by idx with [0,255,0]
stacked[idx]=[0,255,0]

# Back to original image shape
original_image_new=stacked.reshape(original_image.shape[0],original_image.shape[1],3)
# print(original_image_new.shape)
# (451, 521, 3)
© www.soinside.com 2019 - 2024. All rights reserved.