【问题标题】:Convert Image to binary stream将图像转换为二进制流
【发布时间】:2014-06-07 04:34:32
【问题描述】:

我的应用程序有两个方面,一方面我使用 C++ 以便使用 Pleora 的 EBUS SDK 从相机读取帧。当第一次接收到这个流时,在我将缓冲区转换为图像之前,我能够一次读取 16 位流,以便对每个像素执行一些计算,即每个像素存在一个 16 位数据块.

现在后半部分是一个 Django Web 应用程序,我也看到了这个视频输出,这次是通过 ffmpeg、nginx、hls 流。当用户点击视频时,我希望能够获取当前帧和他们点击的坐标,并执行与上面在 C++ 部分中所做的相同的计算。

现在我使用 html5 画布捕获帧,并使用 canvas.toDataURL() 将帧转换为 base64 编码图像,然后将 base64 图像、坐标和帧的尺寸传递给 python通过 AJAX。

在 python 中,我试图以每像素 16 位的方式操作这个 base64 编码的图像。目前我执行以下操作:

pos = json.loads(request.GET['pos'])
str_frame = json.loads(request.GET['frame'])
dimensions = json.loads(request.GET['dimensions'])

pixel_index = (dimensions['width'] * pos['y']) + pos['x'] + 1

b64decoded_frame = base64.b64decode(str_frame.encode('utf-8'))

但是,b64decoded_frame 中的索引数量远远少于图像中的像素,整数值也没有预期的那么高。我已经检查过,图像完好无损,因为我可以将其保存为 png。

总而言之,我如何将 base64 图像转换为序列化二进制流,其中每个像素由 16 位表示。

更新

忘了说我用的是python3.2

经过更多研究后,我认为我正在尝试做的是得到给定像素的 mono16 值。我不确定这是否是我想要做的,但如果有人能解释如何将图像转换为 mono16 或将像素转换为 mono16,我可以探索一下,看看它是否真的是解决方案。

【问题讨论】:

  • 为什么在b64decode之前编码为utf-8
  • 啊,对不起,我忘了提到我正在使用 python3,如果我不这样做,我会给出一个类型错误“预期字节不是 str”。通过将其编码为 utf-8,它确保它是一个字节对象。

标签: python django image image-processing python-imaging-library


【解决方案1】:

我选择的解决方案是将图像转换为 8 位灰度图像,然后将所需像素转换为其 16 位对应像素。解决方案如下所示:

import base64
import io
from PIL import Image

if request.method == 'GET':
    if request.GET['pos'] and request.GET['frame']:
        pos = json.loads(request.GET['pos'])
        str_frame = json.loads(request.GET['frame'])

        # Converts the base64 string into a byte string, we need to encode
        # str_frame as utf-8 first otherwise python3.2 complains about unicode
        b64decoded_frame = base64.b64decode(str_frame.encode('utf-8'))

        # This puts the decoded image into a buffer so that I don't need to save
        # it to disk to use it in PIL
        byte_stream = io.BytesIO(b64decoded_frame)

        # Open the image and convert it to 8-bit greyscale (mono8)
        img = Image.open(byte_stream).convert('L')

        # Get the 8-bit pixel value
        pixel_val = img.getpixel((pos['x'], pos['y']))

        # Convert the 8-bit pixel value to 16-bit by holding the rations
        # i.e. n8 / (2^8 - 1) == x16 / (2^16 - 1)
        pixel_val = int(pixel_val / 255 * 65535)

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 2015-08-27
    • 2012-02-07
    • 2017-12-22
    • 2012-12-15
    • 1970-01-01
    • 2012-05-26
    • 2013-08-13
    相关资源
    最近更新 更多