测试不同大小数组之间的相同性:“DeprecationWarning:elementwise比较失败;这将在将来引发错误”

2024-04-26 12:44:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在处理图像。在管道中,可能会返回原始图像或编辑的图像。更为复杂的是,返回的图像可以具有相同的形状,因此测试相同的形状不是一种方法。根据是否返回原始/编辑的图像,我希望执行不同的步骤。如果使用==符号,则每次都会返回警告:

DeprecationWarning: elementwise comparison failed; this will raise an error in the future

使用以下代码重现警告:

import numpy as np

picture_1 = np.random.randint(0, 256, (100, 100, 3))
picture_2 = picture_1[10:-10, 10:-10]

print(picture_1 == picture_2)

那么,如何测试不同大小的数组是否相等

请注意,对这个问题的现有答案只侧重于避免比较。就我而言,这种比较是有目的的


Tags: 方法图像编辑警告管道np符号步骤
2条回答

Numpy的==用于比较值,因此它不是一种方法。
如果我理解正确,我想你要找的是numpy.ndarray.base

import numpy as np

picture_1 = np.random.randint(0, 256, (100, 100, 3))
picture_2 = picture_1[10:-10, 10:-10]

print(picture_2.base is picture_1) # True

正如在official doc中所述,此代码基于picture_1检查picture_2。换句话说,它检查picture_2是否是picture_1view


或者你想用base作为类似的东西吗?
这将检查从中裁剪picture_2的基picture_1是否与picture_0相同(值)

import numpy as np

picture_0 = np.random.randint(0, 256, (100, 100, 3))
picture_1 = np.copy(picture_0)
picture_2 = picture_1[10:-10, 10:-10]
picture_1_mod = np.copy(picture_0)+1 # mod means modified.
picture_2_mod = picture_1_mod[10:-10, 10:-10]

print(picture_2.base == picture_0) # Array of Trues
print(picture_2_mod.base == picture_0) # Array of Falses

我建议先测试形状是否相等,如果形状相等,再测试项目是否相等。归根结底,如果形状不相等,第二次比较永远不会有用

import numpy as np

picture_1 = np.random.randint(0, 256, (100, 100, 3))
picture_2 = picture_1[10:-10, 10:-10]

print(np.shape(picture_1)==np.shape(picture_2))
if np.shape(picture_1)==np.shape(picture_2):
    print(picture_1 == picture_2)

如果我有误解,仍然试图避免比较,请澄清

相关问题 更多 >