如何使用Boost::GIL从python字节串中读取图片信息?

问题描述 投票:1回答:1

我写了一个函数来从文件头读取图片的宽度和高度。

int read_image_dimensions() {
    namespace bg = boost::gil;

    std::string filepath = "image.png";
    std::ifstream byte_stream(filepath, std::ios::binary);

    int width = 0, height = 0;
    bg::image_read_info<bg::png_tag> png_tag_info;

    png_tag_info = bg::read_image_info(byte_stream, bg::image_read_settings<bg::png_tag>())._info;
    width = png_tag_info._width; height = png_tag_info._height;

    std::cout << width << "x" << height << std::endl;
    return 0;
}

我也不知道如何从python字节中读取图像信息。图片数据来自Blender API我写了一个函数从文件头读取图片的宽度和高度 int read_image_dimensions({ namespace bg = boost: gil; std::string filepath = "image.png"; std::string filepath = "image.png"; std::string filepath = "image.png"; std::string filepath = "image.png".

using namespace boost::python;

int read_image_dimensions(object &image) {
    object image_packed_file = extract<object>(image.attr("packed_file"));
    object packed_data = extract<object>(image_packed_file.attr("data"));
    size_t packed_size = extract<size_t>(image_packed_file.attr("size"));

    // ... 
}
boost boost-python boost-gil
1个回答
1
投票

所以,忽略python的东西,让我们假设你以某种方式掌握了字节。

std::vector<char> pydata;

然后你就可以简单地创建一个流。有多种方法可以实现,但为了提高效率,让我使用Boost Iostreams。

io::stream<io::array_source> byte_stream(pydata.data(), pydata.size());

就这些了 剩下的就是你的了。

现场演示

这表明我的个人资料图片是200x200像素。

#include <boost/gil/extension/io/png.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>

namespace bg = boost::gil;
namespace io = boost::iostreams;

extern std::vector<char> pydata;

int main() {
    io::stream<io::array_source> byte_stream(pydata.data(), pydata.size());

    auto info = bg::read_image_info(
            byte_stream,
            bg::image_read_settings<bg::png_tag>())
        ._info;

    std::cout << "Dimensions: " << info._width << "x" << info._height << "\n";
}

static char const polar_bear[] {
  "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d"
  "\x49\x48\x44\x52\x00\x00\x00\xc8\x00\x00\x00\xc8"
  "\x08\x06\x00\x00\x00\xad\x58\xae\x9e\x00\x00\x20"
  "\x00\x49\x44\x41\x54\x78\x9c\x94\xbd\x59\xb3\x2d"
  "\xcb\x71\x1e\xf6\x65\x56\x75\xf7\x5a\x7b\xef\x73"
  "\xee\x39\x77\xc0\x9d\x31\x03\xc4\x44\xc0\x00\x88"
  // 5623 lines snipped...
  "\x45\x4e\x44\xae\x42\x60\x82"
};

std::vector<char> pydata { std::begin(polar_bear), std::end(polar_bear) };

打印

Dimensions: 200x200
© www.soinside.com 2019 - 2024. All rights reserved.