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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据条件将特定轴替换为其他值相关的知识,希望对你有一定的参考价值。

假设我有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过滤掉了

答案

这是一种方式

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]]])
另一答案

我想用[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]
另一答案

根据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)

以上是关于根据条件将特定轴替换为其他值的主要内容,如果未能解决你的问题,请参考以下文章

R语言dplyr包na_if函数根据条件将数据对象替换为NA值实战

根据闪亮小部件的 if 条件将值替换为数据表

根据规则将数据框中的值替换为其他值

Pandas DataFrame:根据条件替换列中的所有值

Hive查询:根据条件选择一列,另一列值匹配某些特定值,然后将匹配结果创建为新列

根据字符串名称而不是列表视图项位置替换片段并启动活动