如何修复'TypeError:'numpy.ndarray'对象不可调用'

时间:2019-04-07 06:14:48

标签: python opencv

我正在尝试调整1920X1080的大小并将灰度复制到大小为128X32的白色背景上。但是我遇到了这个错误:

 Traceback (most recent call last):
  File "C:/Users/bnsid/Desktop/SimpleHTR-master - Copy/src/SamplePreprocessor.py", line 39, in <module>
    main()
  File "C:/Users/bnsid/Desktop/SimpleHTR-master - Copy/src/SamplePreprocessor.py", line 32, in main
    cv2.imshow('Greyscale_Stretched', target('float32'))
TypeError: 'numpy.ndarray' object is not callable

我的代码:

from __future__ import division
from __future__ import print_function

import random
import numpy as np
import cv2

def main():
    "put img into target img of size imgSize, transpose for TF and normalize gray-values"

    img=cv2.imread("C:\\Users\\bnsid\\OneDrive\\Pictures\\Windows Spotlight Images\\fe22f9acd3313c5e21f8a78dc61a7875a42b489d2f3168336d360c050e85dee0.jpg", cv2.IMREAD_GRAYSCALE)
    imgSize=(128,32)
    if img is None:
        img = np.zeros([imgSize[1], imgSize[0]])

    # dataaugmentation
    stretch = (random.random() - 0.5) # -0.5 .. +0.5
    wStretched = max(int(img.shape[1] * (1 + stretch)), 1) # random width, but at least 1
    img = cv2.resize(img, (wStretched, img.shape[0])) # stretch horizontally by factor 0.5 .. 1.5

    # create target image and copy sample image into it
    (wt, ht) = imgSize
    (h, w) = img.shape
    fx = w / wt
    fy = h / ht
    f = max(fx, fy)
    newSize = (max(min(wt, int(w / f)), 1), max(min(ht, int(h / f)), 1)) # scale according to f (result at least 1 and at most wt or ht)
    img = cv2.resize(img, newSize)
    target = np.ones([ht, wt]) * 255
    target[0:newSize[1], 0:newSize[0]] = img

    cv2.imshow('Greyscale_Stretched', target('float32'))
    k= cv2.waitKey(0) & 0xFF
    if k == 27:  # wait for ESC key to exit
        cv2.destroyAllWindows()
    elif k == ord('s'):  # wait for 's' key to save and exit
        cv2.imwrite('grey.png', target('float32'))
        cv2.destroyAllWindows()
main()

我期望在白色背景上显示灰度图像。

2 个答案:

答案 0 :(得分:0)

通常,当您尝试以function()而不是type[]的方式从numpy调用某些内容时,会发生此问题。供参考,请参见why numpy.ndarray is object is not callable in my simple for python loop

要解决此问题,请尝试将第32行的某些括号更改为括号,因为括号用于函数,括号用于数据类型。我认为这些组合之一会起作用,但我仍然可能是错的。

cv2.imshow('Greyscale_Stretched', target['float32'])
cv2.imshow['Greyscale_Stretched', target('float32')]
cv2.imshow['Greyscale_Stretched', target['float32']]

希望有帮助。

答案 1 :(得分:0)

问题出在target('float32')上 目标是numpy.ndarray,并在其后加上(),您试图像函数一样调用它

对于opencv图像, float32 的范围为 0.0-1.0 ,而 uint8 的范围为 0-255

我可以看到您已经使用target = np.ones([ht, wt]) * 255将目标转换为0-255的范围,因此您想使用'uint8'

现在要解决最初的问题。将numpy数组更改为其他数据类型

target = target.astype('uint8')

target = target.astype('float32') / 255.(除以255,将其返回到0-1.0范围)

或者您可以直接使用它而无需存储新类型cv2.imshow('Greyscale_Stretched', target.astype('uint8'))