简体   繁体   中英

Create a class with a “ndarray” attribute

I want to create a class that looks like this :

class MyStructure:
    def __init__(self, ndarray_type):
        self.data = ndarray_type

And I want to pass an object of this class as an argument to other classes. For example :

class Edit:
    def __init__(self, structureObject):
        self.data = structureObject

    def Gray(self, image):
        r,g,b = image[:,:,0], image[:,:,1], image[:,:,2]
        gray = 0.2989*r + 0.5870*g + 0.1140*b
        return gray

Edit : I get an error when I run this :

from matplotlib.image import imread
im = imread('filename.jpg')
temp1 = MyStructure(im)
temp2 = Edit(temp1)
result = temp2.Gray(temp1)

Traceback (most recent call last):

Line 1 : result = temp2.Gray(temp1)

Line 5, in Gray : r,g,b = image[:,:,0], image[:,:,1], image[:,:,2]

AttributeError: MyStructure instance has no attribute ' getitem '

image is an instance of MyStructure which does not implement [..] access. You have to implement a __getitem__ method of MyStructure which forwards this access to your data attribute to enable this:

class MyStructure:
    def __init__(self, ndarray_type):
        self.data = ndarray_type
    def __getitem__(self, *a):
        return self.data.__getitem__(*a)

What is your intention ?

You get error because you are trying to treat object of class MyStructure as object of class numpy.ndarray and that's not true. The data which you want to assign to r, g, b sits in attribute data of object of class MyStructure . Attribute data is an instance of numpy.ndarray .

If it's still not clear, maybe this will help:

temp1.__class__  # result: <class '__main__.MyStructure'>
temp1.data.__class__  # result: <class 'numpy.ndarray'>

To make it work, you can modify the definition of method Gray to:

def Gray(self, image):
    r,g,b = image.data[:,:,0], image.data[:,:,1], image.data[:,:,2]
    gray = 0.2989*r + 0.5870*g + 0.1140*b
    return gray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM