图像到 python 中的矩阵

Image to matrix in python

我正在尝试将图像转换为矩阵。

values = []
normal = []
for x in (arr):
    for y in (arr):
        if arr[x,y] > 1:
            normal.append(1)
        else:
            normal.append(0)

错误提示:

"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

提前致谢。

看起来 arr 是一个二维数组。 如果你想使用 x, y 作为索引并且 arr 是一个二维数组,那么试试这个:

m, n = arr.shape
for x in range(m):
    for y in range(n):
        if arr[x,y] > 1:
            normal.append(1)
        else:
            normal.append(0)

但是代码看起来不像 pythonic。我会使用 numpy.where 但是如果不知道你真正想做什么就很难提供帮助。