简体   繁体   English

numpy (logical_and vs '&') 语句的顺序导致不同的结果

[英]Order of numpy (logical_and vs '&') statements leads to different results

I have a simple piece of code where I am trying to compare the numpy function logical_and vs the "&" operator.我有一段简单的代码,我试图将 numpy 函数 logical_and 与“&”运算符进行比较。

I encounter a very strange behavior where the order in the which the statements are executed, seem to have an effect on the final result when in fact they shouldn't.我遇到了一个非常奇怪的行为,其中语句执行的顺序似乎对最终结果有影响,而实际上它们不应该。 Weird!奇怪的!

In the below code , if I interchange the final_mask1 and final_mask statement order, it leads to a different value of the variable "test" as well as a different image as an output.在下面的代码中,如果我交换 final_mask1 和 final_mask 语句顺序,它会导致变量“test”的不同值以及不同的图像作为输出。 This is for the case where I have final_mask as output.这是针对我将 final_mask 作为输出的情况。 Am I missing something here?我在这里错过了什么吗? How can I resolve this?我该如何解决这个问题? TIA TIA

import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
photo_data = misc.imread('./sd-3layers.jpg')
red_mask = photo_data[:, : ,0] < 150
green_mask = photo_data[:, : ,1] > 100
blue_mask = photo_data[:, : ,2] < 100

final_mask1 = np.logical_and(red_mask, green_mask, blue_mask)
final_mask = red_mask & green_mask & blue_mask

test = (final_mask1 == final_mask)
print(np.all(test))
photo_data[final_mask] = 0
plt.figure(figsize=(15,15))
plt.imshow(photo_data)

Looking up the documentation of logical_and , one finds that it compares only two arrays, and that the third argument is used for storing results in a different array.查看logical_and 的文档,发现它只比较两个数组,而第三个参数用于将结果存储在不同的数组中。 You can use reduce to avoid having to write to calls to logical_and , so what you're trying to do ends up looking like您可以使用reduce来避免写入对logical_and调用,因此您尝试执行的操作最终看起来像

np.logical_and.reduce((red_mask, green_mask, blue_mask))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM