如何在Python中创建dtype cl.cltypes.uint2变量

2024-06-16 08:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在Python中为pyopencl创建类型为cl.cltypes.uint2的变量。 现在我这样创建它:

key = np.array([(0x01020304, 0x05060708)], dtype=cl.cltypes.uint2)[0]

它绝对是肮脏的黑客(如何以更干净的方式创建它

这:key = cl.cltypes.uint2((0x01020304, 0x05060708))

由于错误而无法工作:'numpy.dtype' object is not callable


Tags: keypyopenclnumpy类型objectiscl错误
1条回答
网友
1楼 · 发布于 2024-06-16 08:23:23

快速阅读链接表明它正在生成复合数据类型。如果不加载并运行它,我认为您的示例类似于

In [164]: dt = np.dtype([('x',np.uint16),('y',np.uint16)])                                             
In [165]: np.array([(0x01020304, 0x05060708)], dtype=dt)                                               
Out[165]: array([(772, 1800)], dtype=[('x', '<u2'), ('y', '<u2')])
In [166]: dt((0x01020304, 0x05060708))                                                                 
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-166-d71cce4777b9> in <module>
  > 1 dt((0x01020304, 0x05060708))

TypeError: 'numpy.dtype' object is not callable

并从阵列中取出一条记录:

In [167]: np.array([(0x01020304, 0x05060708)], dtype=dt)[0]                                            
Out[167]: (772, 1800)
In [168]: _.dtype                                                                                      
Out[168]: dtype([('x', '<u2'), ('y', '<u2')])

化合物dtype永远不可调用

我认为0d“scalar”数组比使用dtype函数创建的对象更好(尽管它们有类似的方法)

对于复合数据类型:

In [228]: v = np.array((0x01020304, 0x05060708), dtype=dt)                                             
In [229]: v                                                                                            
Out[229]: array((772, 1800), dtype=[('x', '<u2'), ('y', '<u2')])
In [230]: type(v)                                                                                      
Out[230]: numpy.ndarray
In [231]: v[()]                                                                                        
Out[231]: (772, 1800)
In [232]: type(_)                                                                                      
Out[232]: numpy.void
In [233]: _231.dtype                                                                                   
Out[233]: dtype([('x', '<u2'), ('y', '<u2')])

您可以将这样的数组强制转换为recarray并获得一个record对象,但我认为创建这些对象并不容易

In [234]: v.view(np.recarray)                                                                          
Out[234]: 
rec.array((772, 1800),
          dtype=[('x', '<u2'), ('y', '<u2')])
In [235]: _.x                                                                                          
Out[235]: array(772, dtype=uint16)
In [238]: v.view(np.recarray)[()]                                                                      
Out[238]: (772, 1800)
In [239]: type(_)                                                                                      
Out[239]: numpy.record

相关问题 更多 >