繁体   English   中英

将使用 PIL 加载的图像转换为 Cimg 图像对象

[英]Convert an image loaded using PIL to a Cimg image object

我正在尝试将使用PIL加载的图像转换为 Cimg 图像对象。 我知道 Cimg 是一个 C++ 库,而 PIL 是一个 python 成像库。 给定一个图像 url,我的目标是计算图像的pHash而不将其写入磁盘。 pHash 模块与Cimg 图像对象一起工作,它已用 C++ 实现。 所以我打算使用python扩展绑定将所需的图像数据从我的python程序发送到c++程序。 在以下代码片段中,我从给定的 url 加载图像:

//python code sniplet   
import PIL.Image as pil

file = StringIO(urlopen(url).read())
img = pil.open(file).convert("RGB")

我需要构建的 Cimg 图像对象如下所示:

CImg  ( const t *const  values,  
    const unsigned int  size_x,  
    const unsigned int  size_y = 1,  
    const unsigned int  size_z = 1,  
    const unsigned int  size_c = 1,  
    const bool  is_shared = false  
)

我可以使用 img.size 获取 width(size_x) 和 height(size_y) 并将其传递给 c++。 我不确定如何填充 Cimg 对象的“值”字段? 使用什么样的数据结构将图像数据从python传递到c++代码?

另外,有没有其他方法可以将 PIL 图像转换为 Cimg?

我假设您的主应用程序是用 Python 编写的,并且您想从 Python 调用 C++ 代码。 您可以通过创建一个“ Python 模块”来实现这一点,该模块将向Python公开所有本机 C/C++ 功能。 您可以使用 SWIG 之类的工具来简化您的工作。

这是我想到的您问题的最佳解决方案。

将图像从 Python 传递到基于 C++ CImg 的程序的最简单方法是通过管道。

所以这是一个基于 C++ CImg 的程序,它从stdin读取图像并将一个虚拟的 pHash 返回给 Python 调用者——这样你就可以看到它是如何工作的:

#include "CImg.h"
#include <iostream>

using namespace cimg_library;
using namespace std;

int main()
{
    // Load image from stdin in PNM (a.k.a. PPM Portable PixMap) format
    cimg_library::CImg<unsigned char> image;
    image.load_pnm("-");

    // Save as PNG (just for debug) rather than generate pHash
    image.save_png("result.png");

    // Send dummy result back to Python caller
    std::cout << "pHash = 42" << std::endl;
}

这是一个 Python 程序,它从 URL 下载图像,将其转换为 PNM/PPM( “Portable PixMap” )并将其发送到 C++ 程序,以便它可以生成并返回 pHash:

#!/usr/bin/env python3

import requests
import subprocess
from PIL import Image
from io import BytesIO

# Grab image and open as PIL Image
url = 'https://i.stack.imgur.com/DRQbq.png'
response = requests.get(url)
img = Image.open(BytesIO(response.content)).convert('RGB')

# Generate in-memory PPM image which CImg can read without any libraries
with BytesIO() as buffer:
    img.save(buffer,format="PPM")
    data = buffer.getvalue()

# Start CImg passing our PPM image via pipe (not disk)
with subprocess.Popen(["./main"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc:
    (stdout, stderr) = proc.communicate(input=data)

print(f"Returned: {stdout}")

如果你运行 Python 程序,你会得到:

Returned: b'pHash = 42\n'

暂无
暂无

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

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