Python - 数组在传递给函数时变为标量变量

问题描述 投票:0回答:2

我正在尝试创建一个简单的python脚本,当给出照片时,首先将其转换为灰度,然后将其带入多种颜色。例如,如果传入的颜色数为2,则将更改灰度图像,使每个像素为投影黑(0)或亮白(255)。

但是,当调用我的函数'getGreyscaleValue'用于确定每个像素的灰度值时,我收到一个错误。似乎在将数组'bandWidthArray'和'colorsArray'传递给函数时,它们从数组变为标量变量'0.0'。运行以下脚本并观察打印值应该复制问题:

import numpy as np
from PIL import Image

numberOfColors = 2;
greyscaleRange=255;

col = Image.open("IMG_5525.JPG")
gray = col.convert('L') # Make grayscale

y=np.asarray(gray.getdata(),dtype=np.float64).reshape((gray.size[1],gray.size[0]))

def getGreyScaleValue(x, bandWidthArray, colorsArray):
    print(bandWidthArray)
    print(colorsArray)
    for i in range(1, bandWidthArray.len):
        if(int(round(x))<int(round(bandWidthArray[i]))):
            return colorsArray[i-1]
    return 255

bandWidthArray = np.linspace(0, greyscaleRange, numberOfColors+1)
colorsArray = np.linspace(0, greyscaleRange, numberOfColors)
getGreyScaleValue = np.vectorize(getGreyScaleValue)

print(bandWidthArray)
print(colorsArray)

y = getGreyScaleValue(y, bandWidthArray, colorsArray)

y=np.asarray(y,dtype=np.uint8) #if values still in range 0-255!
w=Image.fromarray(y,mode='L')
w.save('out.jpg')

堆栈跟踪如下:

PS C:\python\pythonimages> python imgChange1.py
[   0.   127.5  255. ]
[   0.  255.]
0.0
0.0
Traceback (most recent call last):
  File "imgChange1.py", line 27, in <module>
    y = getGreyScaleValue(y, bandWidthArray, colorsArray)
  File "C:\Users\Jack\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\function_base.py", line 2734, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "C:\Users\Jack\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\function_base.py", line 2804, in _vectorize_call
    ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)

  File "C:\Users\Jack\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\function_base.py", line 2764, in _get_ufunc_and_otypes
    outputs = func(*inputs)
  File "imgChange1.py", line 15, in getGreyScaleValue
    for i in range(1, bandWidthArray.len):
AttributeError: 'numpy.float64' object has no attribute 'len'
python numpy
2个回答
0
投票
for i in range(1, bandWidthArray.len):

可以改为

for i in range(1, bandWidthArray.size):


>>> qa = np.array([1,3,5])
>>> qa.size
3

0
投票

更改:

for i in range(1, bandWidthArray.len):

至:

for i in range(1, len(bandWidthArray)):

NumPy数组没有len方法。

此外,不要向量化您的功能。删除此行:

getGreyScaleValue = np.vectorize(getGreyScaleValue)
© www.soinside.com 2019 - 2024. All rights reserved.