将使用PIL加载的图像转换为img图像对象
Convert an image loaded using PIL to a Cimg image object
我正在尝试将使用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'
相关文章:
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 将 BGR 图像转换为 jpeg 格式的 base64 字符串
- C++ Gdi+将图像转换为灰度
- 将 BMP 图像转换为灰度
- Qmage:如何将灰色图像转换为RGB热图
- 更快地将卤化物图像转换为 opencv 垫?
- 将原始视频图像转换为VPX编码器的I420
- ROS中未定义的参考误差到OpenCV图像转换器
- 如何将图像转换为灰度 opengl c++
- 将 24 位".bmp"图像转换为黑白/单色图像的可能算法是什么?
- 在OpenCV中将灰度图像转换为单色
- RGB到XYZ,图像转换
- 如何将图像转换为C 中的RGB数据值
- OpenCV:将图像转换为C++数组
- 从两个图像转换的OpenCV
- 使用某些系数将图像转换为灰度的最快方法
- 将RGB颜色图像转换为OpenCV C 中的索引颜色图像类型
- CUDA OPENCV CVTCOLOR调用不会将图像转换为不同的格式
- 将 RGB 图像转换为 3 个 HSI 输出
- VTK 将 2D 图像转换为 3D (C++)