Патч обезьяны не работает в инструкции __init__
Я пытаюсь исправить функцию дополнения из пакета clodsa, чтобы читать файлы с пользовательскими именами .json вместо того, чтобы придерживаться их формата, поэтому вместо /annotations.json создайте new_name.json:
!pip install clodsa
??augmentor
Type: COCOLinearInstanceSegmentationAugmentor
String form: <clodsa.augmentors.cocoLinearInstanceSegmentationAugmentor.COCOLinearInstanceSegmentationAugmentor object at 0x7fbc1f48de50>
File: /usr/local/lib/python3.7/dist-packages/clodsa/augmentors/cocoLinearInstanceSegmentationAugmentor.py
Source:
class COCOLinearInstanceSegmentationAugmentor(IAugmentor):
def __init__(self, inputPath, parameters):
IAugmentor.__init__(self)
self.imagesPath = inputPath
self.annotationFile = inputPath + "/annotations.json"
# output path represents the folder where the images will be stored
if parameters["outputPath"]:
self.outputPath = parameters["outputPath"]
else:
raise ValueError("You should provide an output path in the parameters")
self.ignoreClasses = parameters.get("ignoreClasses",set())
def readImagesAndAnnotations(self):
(self.info, self.licenses, self.categories, self.dictImages, self.dictAnnotations) \
= readCOCOJSON(self.annotationFile)
Я пробовал следующее, чтобы исправить путь self.annotationFile:
def new_init(self, inputPath, parameters):
IAugmentor.__init__(self)
self.imagesPath = inputPath
self.annotationFile = inputPath + "/new_name.json"
# output path represents the folder where the images will be stored
if parameters["outputPath"]:
self.outputPath = parameters["outputPath"]
else:
raise ValueError("You should provide an output path in the parameters")
self.ignoreClasses = parameters.get("ignoreClasses",set())
augmentor.__init__ = new_init
Когда я запускаю новый init, он действительно показывает пропатченный init с помощью ?? augmentor. в этом
Но когда я запускаю полный код, он просто возвращается к использованию старого оператора init:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-15-30ca2128bdb6> in <module>()
1 #Perform the augmentations
----> 2 augmentor.applyAugmentation()
2 frames
/usr/local/lib/python3.7/dist-packages/clodsa/augmentors/cocoLinearInstanceSegmentationAugmentor.py in applyAugmentation(self)
87
88 def applyAugmentation(self):
---> 89 self.readImagesAndAnnotations()
90
91 newannotations = Parallel(n_jobs=-1)(delayed(readAndGenerateInstanceSegmentation)
/usr/local/lib/python3.7/dist-packages/clodsa/augmentors/cocoLinearInstanceSegmentationAugmentor.py in readImagesAndAnnotations(self)
84 def readImagesAndAnnotations(self):
85 (self.info, self.licenses, self.categories, self.dictImages, self.dictAnnotations) \
---> 86 = readCOCOJSON(self.annotationFile)
87
88 def applyAugmentation(self):
/usr/local/lib/python3.7/dist-packages/clodsa/augmentors/utils/readCOCOJSON.py in readCOCOJSON(jsonPath)
5
6 def readCOCOJSON(jsonPath):
----> 7 with open(jsonPath) as f:
8 data = json.load(f)
9
FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/annotations.json'
Что я делаю не так?
1 ответ
Я посмотрел исходный код класса COCOLinearInstanceSegmentationAugmentor (репозиторий для этого проекта немного запутался - они зафиксировали двоичный
.pyc
файлы и прочая ерунда, но это в сторону ...)
Похоже, вы сможете сделать это, просто создав подклассы:
class MyCOCOLinearInstanceSegmentationAugmentor(COCOLinearInstanceSegmentationAugmentor):
def __init__(self, inputPath, parameters):
super().__init__(inputPath, parameters)
self.annotationFile = os.path.join(inputPath, 'new_name.json')
в качестве альтернативы, поскольку
self.annotationsFile
это просто нормальный атрибут после
COCOLinearInstanceSegmentationAugmentor
создается экземпляр, но перед вызовом каких-либо методов, использующих этот атрибут, вы можете просто присвоить ему новое значение, например:
augmentor.annotationFile = <whatever you want>