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

Convert an image loaded using PIL to a Cimg image object

本文关键字:图像 转换 img 对象 PIL 加载      更新时间:2023-10-16

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

//python code sniplet   
import PIL.Image as pil
file = StringIO(urlopen(url).read())
img = pil.open(file).convert("RGB")

我需要构造的img图像对象如下所示:

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  
)

我可以得到宽度(size_x)和高度(size_y)使用img。大小,并可以传递给c++。我不确定如何填写Cimg对象的"值"字段?使用什么样的数据结构将图像数据从python传递到c++代码?

另外,是否有其他方法将PIL图像转换为Cimg?

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

这是我想到的解决你问题的最好办法。

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

这是一个基于c++ cim的程序,它从stdin读取图像并向Python调用者返回一个虚拟pHash -以便您可以看到它是如何工作的:

#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 = 42n'