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

时间:2017-12-27 09:41:19

标签: python numpy

我正在尝试创建一个简单的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'

2 个答案:

答案 0 :(得分:0)

变化:

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

为:

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

NumPy数组没有len方法。

此外,不要对你的功能进行矢量化。删除这一行:

getGreyScaleValue = np.vectorize(getGreyScaleValue)

答案 1 :(得分:0)

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

可以更改为

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


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