Python类调用onVideo()报TypeError:缺少self参数的解决求助
解决Python类方法调用的TypeError问题
我跟着YouTube教程做目标检测软件,到10分钟时卡壳了。加了自己的测试视频验证代码,运行时报错:
TypeError: onVideo() missing 1 required positional argument: 'self'
我对Python类的用法不太熟,明明创建了Detector类的实例,调用onVideo()还是触发这个错误,贴出相关代码和错误栈,求解决这个TypeError。
Detector类代码
import cv2 import numpy as np import time class Detector: def __init__(self, videoPath, configPath, modelPath, classesPath): self.videoPath = videoPath self.configPath = configPath self.modelPath = modelPath self.classesPath = classesPath self.net = cv2.dnn_DetectionModel(self.modelPath, self.configPath) self.net.setInputSize(320,320) self.net.setInputScale(1.0/127.5) self.net.setInputMean((127.5, 127.5, 127.5)) self.net.setInputSwapRB(True) self.readClasses() def readClasses(self): with open(self.classesPath, 'r') as f: self.classesList = f.read().splitlines() self.classesList.insert(0, '__Background__') self.colorList = np.random.uniform(low=0, high=255, size=(len(self.classesList), 3)) def onVideo(self): cap = cv2.VideoCapture(self.videoPath) if not cap.isOpened(): print("Error opening the file...") return success, image = cap.read() while success: classLabelIDs, confidences, bboxs = self.net.detect(image, confThreshold=0.4) bboxs = list(bboxs) confidences = list(np.array(confidences).reshape(1, -1)[0]) confidences = list(map(float, confidences)) bboxIdx = cv2.dnn.NMSBoxes(bboxs, confidences, score_threshold=0.5, nms_threshold=0.2) if len(bboxIdx) != 0: for i in range(len(bboxIdx)): bbox = bboxs[np.squeeze(bboxIdx[i])] classConfidence = confidences[np.squeeze(bboxIdx[i])] classLabelID = np.squeeze(classLabelIDs[np.squeeze(bboxIdx[i])]) classLabel = self.classesList[classLabelID] classColor = [int(c) for c in self.colorList[classLabelID]] displayText = "{}:{:.2f}".format(classLabel, classConfidence) x, y, w, h = bbox cv2.putText(image, displayText, (x, y-10), cv2.FONT_HERSHEY_PLAIN, 1, classColor, 2) cv2.rectangle(image, (x, y), (x+w, y+h), color=classColor, thickness=1) cv2.imshow("Result", image) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break success, image = cap.read() cv2.destroyAllWindows()
主程序代码
from Detector import * import os def main(): videoPath = "test_videos/gamevid.mp4" configPath = os.path.join("model_data", "ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt") modelPath = os.path.join("model_data", "frozen_inference_graph.pb") classesPath = os.path.join("model_data", "coco.names") detector = Detector(videoPath, configPath, modelPath, classesPath) detector.onVideo() if __name__ == '__main__': main()
错误信息
Traceback (most recent call last): File "c:\Users\mondo\Desktop\Final DT software\real_time_object_detection_cpu-main\model_data\DetectorMain.py", line 12, in main Detector.onVideo() TypeError: onVideo() missing 1 required positional argument: 'self'
问题原因
从错误栈能明确看到,你实际运行时调用的是Detector.onVideo()(直接调用类的方法),而非你贴出来的detector.onVideo()(用实例调用方法)。虽然你提供的主程序代码写法正确,但实际运行的代码肯定写错了,直接调用了类的方法,没有传入实例对象。
修复方案
- 打开你的主程序文件
DetectorMain.py,找到调用onVideo的代码行:- 把错误的
Detector.onVideo()改成detector.onVideo() - 确保你是用之前创建的实例
detector来调用方法,而不是类Detector本身
- 把错误的
- 保存修改后重新运行程序,错误即可解决。
补充说明
Python中,类的实例方法(比如onVideo)第一个参数必须是self,它代表类的实例本身。当你用实例调用方法时,Python会自动把实例作为self参数传入;但如果直接用类调用方法,就需要手动传入实例,否则就会报缺少self参数的错误。
内容的提问来源于stack exchange,提问作者Charlie
相关产品推荐
相关产品推荐

