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

时间:2019-04-14 00:05:01

标签: python numpy

假设我的原图图像为(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],...])都由{{ 1}}

3 个答案:

答案 0 :(得分:1)

这是一种方法

Properties props = new Properties();

...

final StreamsBuilder builder = new StreamsBuilder();
Pattern pattern = Pattern.compile(<YOUR_INPUT_TOPIC_PATTERN>);
KStream<String, String> source = builder.stream(pattern);

...

source.mapValues((k,v) -> {
     Gson gson = new Gson();
     Map map = gson.fromJson(v, Map.class);

     // here is your transformation logi

     return v;
}).to(<YOUR_OUTPUT_TOPIC>);

...

final Topology topology = builder.build();
final KafkaStreams streams = new KafkaStreams(topology, props);

...

streams.start();

数据输入

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

答案 1 :(得分: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]

答案 2 :(得分: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)