简体   繁体   English

将 8 位值转换为 4 位值并在 python 中的一个字节中保存 2 个 4 位值的快速且节能的方法

[英]fast and power efficient way to convert 8bit values to 4bit values and save 2 4bit values in one byte in python

i want to make a video stream program over udp, with opencv, i want to make a compression by converting the 255 color values into 16 color values, because it will save trafic by half and the quality isnt that bad.我想在udp上制作一个视频stream节目,用opencv,我想通过将255个颜色值转换为16个颜色值来进行压缩,因为它可以节省一半的流量而且质量也不错。 i know how to convert 255 values to 16 values:我知道如何将 255 个值转换为 16 个值:

opencvimg = numpy.multiply(opencvimg//16,16)

but i dont know a efficient way to get two values into 1 byte to save traffic.但我不知道将两个值放入 1 个字节以节省流量的有效方法。 it has to be efficient cause i want it to run on a rpi (full code on github.com/Open-ATS-Github).它必须高效,因为我希望它在 rpi 上运行(github.com/Open-ATS-Github 上的完整代码)。

I think you mean this:我想你的意思是:

import numpy as np

# Make synthetic data
x = np.arange(256, dtype=np.uint8)

# Take pairs of elements shifted by 4 bits and OR together
d2by4 = (x[::2] & 0xf0) | (x[1::2] >> 4)

In [16]: d2by4.dtype
Out[16]: dtype('uint8')

In [21]: d2by4
Out[21]: 
array([  0,   0,   0,   0,   0,   0,   0,   0,  17,  17,  17,  17,  17,
        17,  17,  17,  34,  34,  34,  34,  34,  34,  34,  34,  51,  51,
        51,  51,  51,  51,  51,  51,  68,  68,  68,  68,  68,  68,  68,
        68,  85,  85,  85,  85,  85,  85,  85,  85, 102, 102, 102, 102,
       102, 102, 102, 102, 119, 119, 119, 119, 119, 119, 119, 119, 136,
       136, 136, 136, 136, 136, 136, 136, 153, 153, 153, 153, 153, 153,
       153, 153, 170, 170, 170, 170, 170, 170, 170, 170, 187, 187, 187,
       187, 187, 187, 187, 187, 204, 204, 204, 204, 204, 204, 204, 204,
       221, 221, 221, 221, 221, 221, 221, 221, 238, 238, 238, 238, 238,
       238, 238, 238, 255, 255, 255, 255, 255, 255, 255, 255], dtype=uint8)

That says... "take the high nibble of every second element of x starting with the first and OR it together with the upper nibble shifted right by 4 bits of every second element of x starting with the second."这就是说...... “从第一个开始取 x 的每个第二个元素的高半字节,并将它与从第二x开始的x的每个第二个元素的高半字节右移 4 位。”

There is a solution that involves no explicit arithmetic: you can build a full lookup-table of 256 x 256 entries, giving the packed result for a pair of input bytes.有一个不涉及显式算法的解决方案:您可以构建一个 256 x 256 条目的完整查找表,给出一对输入字节的打包结果。

If such a table seems unreasonably large, think that you are working with images, which are even larger.如果这样的表格看起来大得不合理,请认为您正在处理更大的图像。

Whether it is better to work with a flat vector or with a matrix and if cache effects will not ruin the effort is a matter of experimentation.使用平面向量还是使用矩阵更好,以及缓存效果是否会破坏工作效果是一个实验问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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