[英]Need some help in Python with class
我確實需要一些幫助來理解Python和類。
我正在用幾種方法定義一個ImageProcessing類。
class ImageProcessing:
"""
Class containing different processing operations
"""
def __init__(self, name, height, width):
""" Defining name, height and width of image processing object """
self.name = name
self.height = height
self.width = width
# several methods here with def.
# These methods mainly used some open cv operations.
def masking(self):
""" Method to mask | All masks are applied manually
- self MUST BE a numpy array or a scalar
"""
mask = cv2.rectangle(self, (0,0), (250,1200), (0,0,0), -1)
return(mask)
當我創建一個對象時,它被定義為屬於ImageProcessing類。
diff = ImageProcessing("diff",1200,1600)
diff = diff.masking()
因此,這個名為“ diff”的對象無法使用我在類ImageProcessing中定義的其他方法,例如遮罩,因為這些方法正在等待使用標量或數組,並且我的對象的類型為ImageProcessing。
我迷路了! 在這個基本的東西上需要一些幫助。 我如何在一個類中定義一個對象,並賦予它供數組方法(位於同一類中的方法)使用的權限?
您正在嘗試使用一個期望在新ImageProcessing
對象上使用Numpy數組(或標量)的函數。 這就像試圖修飾帽子架-沒有任何意義。
實際上, 您編寫的函數的文檔字符串指定輸入必須為Numpy數組或標量。
您可以嘗試創建一個Numpy數組作為函數的一部分:
import numpy as np
def masking(self):
new_numpy_array = np.empty((self.width, self.height))
mask = cv2.rectangle(new_numpy_array, (0,0), (250,1200), (0,0,0), -1)
return(mask)
或者,如果您可能經常做這種事情,則可以與對象同時創建Numpy數組:
import numpy as np
def __init__(self, name, height, width):
""" Defining name, height and width of image processing object """
self.name = name
self.height = height
self.width = width
self.numpy_repr = np.empty((width, height))
def masking(self):
mask = cv2.rectangle(self.numpy_repr, (0,0), (250,1200), (0,0,0), -1)
return(mask)
無論哪種情況, diff = diff.masking()
都不會按照您想要的方式工作,因為cv2.rectangle(...)
返回一個數組,而不是ImageProcessing
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.