对于“文本”,无法将类型 'function' 的对象转换为 'str'

Can't convert object of type 'function' to 'str' for 'text

大家好 很抱歉我是 python 编程的新手 很抱歉,如果我问这个,即使这是基本的或不是。有人可以帮我吗?问题是我想将我的 Pyserial 从我的 Arduino 温度传感器读取的数据放入,但我不知道如何。

这里是温度到 pyserial 的代码:

def tempe():
    import serial
    import time


    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string 
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()

这是我想在 opencv 上的 PutText 中显示的完整代码:

def offrecog():

screen2.destroy() <=dont mind this
screen.destroy()  <= dont mind this
def recog2(img, classifier, scaleFactor,miNeighbors, color, text, clf):
    image =  cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    features = classifier.detectMultiScale(image, scaleFactor, miNeighbors)

    for (x,y,w,h) in features:
        cv2.rectangle(img, (x,y),(x+w,y+h), color, 2)

        id, pred = clf.predict(image [y:y+h, x:x+w])
        confidence = int(100*(1-pred/300))

        databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
        )

        mycursor = databases.cursor()

        mycursor.execute("SELECT names FROM record WHERE ids= " + str(id))
        datas = mycursor.fetchone()
        datas = "+".join(datas)

        cursor2 = databases.cursor()
        cursor2.execute("SELECT course_year FROM record WHERE ids= " + str(id))
        datas1 = mycursor.fetchone()
        datas1 = "+".join(datas1)

        cursor3 = databases.cursor()
        cursor3.execute("SELECT positions FROM record WHERE ids= " + str(id))
        datas2 = mycursor.fetchone()
        datas2 = "+".join(datas2)

        if confidence>70:
            cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, tempe, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            markattend(datas,datas1,datas2)
            
        else:

            cv2.putText(img, "UNKNOWN", (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 1, cv2.LINE_AA)

    return img

faceCascade = cv2.CascadeClassifier("C:\Users\So_Low\Desktop\final_recog\haarcascade_frontalface_default.xml")

clf = cv2.face.LBPHFaceRecognizer_create()
clf.read("trained.xml")

video_capture = cv2.VideoCapture(0)

while True:
    ret, img = video_capture.read()
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
    cv2.imshow("FACE RECOGNITION", img)

    if cv2.waitKey(1) & 0xFF == ord('!'):
        break
video_capture.release()
cv2.destroyAllWindows()
screen2.destroy()

我在 运行 时遇到了这个错误:

File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 97, in recog2
    cv2.putText(img, wew, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'function' to 'str' for 'text'
>  - Can't convert object of type 'function' to 'str' for 'text'

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-u4kjpz2z\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

[Done] exited with code=0 in 14.22 seconds

[Running] python -u "c:\Users\So_Low\Desktop\Offrecog\offrecog.py"
Exception in Tkinter callback
Traceback (most recent call last):
  File "I:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 136, in login_verify
    offrecog()
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 113, in offrecog
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 95, in recog2
    cv2.putText(img, temps, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'module' to 'str' for 'text'
>  - Can't convert object of type 'module' to 'str' for 'text'

即使我不将温度代码放入函数中,它 运行 在 opencv 之前的 pyserial 1st。 请帮助我不知道该怎么办。请

大概您想对温度进行 50 次采样,然后 return 一个值?

def get_temp(ser, num_samples=50):
    float_vals = [float(ser.readline()) for _ in range(num_samples)]
    avg_val = sum(float_vals)/len(float_vals) 
    return str(avg_val) # convert to string for open cv

然后在您的 opencv 调用中使用 get_temp(ser) 而不是 tempe

其中 ser 是一个已经打开的串行实例

如果采集 50 个样本太慢那么你总是可以用 get_temp(ser,5) 采集更少的样本例如只采集 5 个样本......如果你想要模式或中位数而不是平均值那么我会推荐只使用 numpy.modenumpy.median 而不是计算它(使用 numpy.mean 可能比手动计算平均值更快)

您的函数 tempe 似乎没有返回任何内容。 为什么不尝试在函数末尾添加 return data(在 ser.close() 之后)?

def tempe():
    import serial
    import time


    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string 
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()
    return data <= try adding this

您可能需要注意,您不能直接将此列表放入 addText 命令中,因为 cv2 似乎不支持从除字符串以外的任何内容中获取数据。我认为您可以使用 for 循环使用 for text in tempe() 遍历 tempe() 并用它做任何您想做的事。同样,取决于您的具体用例。