[英]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 傳遞到基於 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.