我想构造一个继承自numpy.ndarray的类,以便它可以作为numpy数组(+,-,*,/,...)进行常规操作。我唯一要更改的是我们访问数据中项目的方式。例如:
import numpy as np
from PIL import Image
class Data(np.ndarray):
"""
Something magical here
"""
img = np.asarray(Image.open('lena.jpg'))
data = img.view(Data)
data['Red'] #equivalent to img[:,:,0]
normalized_data = data/255. #normalize the data
谁能帮我解决这个问题?谢谢和亲切的问候
参考方案
您将要重写__getitem__方法。这是另一个可以提供一些直觉的问题:Understanding __getitem__ method。
链接到文档:https://docs.python.org/3/reference/datamodel.html#object.__getitem__
如果要更改设置值,请覆盖__setitem__
一个例子:
def __getitem__(self, key):
""" Controls how values are 'gotten'. """
if key == 'red':
return self.data[:,:,0]
Python uuid4,如何限制唯一字符的长度 - python在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
numpy.savetxt“元组索引超出范围”? - python我试图在文本文件中写几行,这是我使用的代码:import numpy as np # Generate some test data data = np.arange(0.0,1000.0,50.0) with file('test.txt', 'w') as outfile: outfile.write('…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
Python GPU资源利用 - python我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…