是否有将二进制 (0|1) numpy 数组转换为整数或二进制字符串的快捷方式?F.e.
Is there a shortcut to Convert binary (0|1) numpy array to integer or binary-string ? F.e.
b = np.array([0,0,0,0,0,1,0,1])
=> b is 5
np.packbits(b)
有效,但仅适用于 8 位值..如果 numpy 是 9 个或更多元素,它会生成 2 个或更多 8 位值.另一种选择是返回一个字符串 0|1 ...
works but only for 8 bit values ..if the numpy is 9 or more elements it generates 2 or more 8bit values. Another option would be to return a string of 0|1 ...
我目前做的是:
ba = bitarray()
ba.pack(b.astype(np.bool).tostring())
#convert from bitarray 0|1 to integer
result = int( ba.to01(), 2 )
太丑了!!!
一种方法是使用 dot-product 与 2-powered 范围数组 -
One way would be using dot-product with 2-powered range array -
b.dot(2**np.arange(b.size)[::-1])
示例运行 -
In [95]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])
In [96]: b.dot(2**np.arange(b.size)[::-1])
Out[96]: 1285
或者,我们可以使用按位左移运算符来创建范围数组,从而获得所需的输出,就像这样 -
Alternatively, we could use bitwise left-shift operator to create the range array and thus get the desired output, like so -
b.dot(1 << np.arange(b.size)[::-1])
如果对时间感兴趣 -
In [148]: b = np.random.randint(0,2,(50))
In [149]: %timeit b.dot(2**np.arange(b.size)[::-1])
100000 loops, best of 3: 13.1 µs per loop
In [150]: %timeit b.dot(1 << np.arange(b.size)[::-1])
100000 loops, best of 3: 7.92 µs per loop
<小时>
逆向处理
要检索二进制数组,请使用 np.binary_repr 以及 np.fromstring -
To retrieve back the binary array, use np.binary_repr alongwith np.fromstring -
In [96]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])
In [97]: num = b.dot(2**np.arange(b.size)[::-1]) # integer
In [98]: np.fromstring(np.binary_repr(num), dtype='S1').astype(int)
Out[98]: array([1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1])
这篇关于将二进制(0 | 1)numpy转换为整数或二进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在python中的感兴趣区域周围绘制一个矩形How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
如何使用 OpenCV 检测和跟踪人员?How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
如何在图像的多个矩形边界框中应用阈值?How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
如何下载 Coco Dataset 的特定部分?How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
根据文本方向检测图像方向角度Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
使用 Opencv 检测图像中矩形的中心和角度Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)