使用 ImageMagick C API 中的 MagickGetImageHistogram 方法

我一直在使用 ImageMagick 的 C API,使用 LuaJIT 和 FFI 库以及 magick lua 模块。现在我想使用 MagickGetImageHistogram 方法。所以,当涉及到传递参数时,请检查我的以下代码。

***image.lua***

local len = ffi.new("size_t[?]", 5)
local t = handle_result(self, lib.MagickGetImageHistogram(self.wand, len))

***lib.lua***

local ffi = require("ffi")
local lib
ffi.cdef([[  typedef void MagickWand;
typedef void PixelWand;

typedef int MagickBooleanType;
typedef int ExceptionType;
typedef int ssize_t;
typedef int CompositeOperator;
typedef int GravityType;
typedef int OrientationType;
typedef int InterlaceType;
typedef char DistortMethod[];

void MagickWandGenesis();
MagickWand* NewMagickWand();

PixelWand **MagickGetImageHistogram(MagickWand *wand, size_t *number_colors);

所以我确定我的第一个参数是正确的,但不确定第二个参数。并且它将图像直方图作为 PixelWand wands 数组返回。那么我该如何将它转换为 LuaJIT 结构?

点赞
用户438117
用户438117

我不确定此问题中的 lua 部分,但 MagickGetImageHistogram 的期望行为如下:

  1. 该方法将返回一个像素指针数组。
  2. 参数 size_t *number_colors 将被更新为数组中像素的数量。
  3. 数组中的每个像素将需要调用方法 PixelGetColorCount 来检索图像使用的像素总和。

以下是 C 语言的快速示例。

#include <stdio.h>
#include <wand/MagickWand.h>

int main(int argc, const char * argv[]) {
    // Prototype vars
    MagickWand * wand;
    PixelWand ** histogram;
    size_t histogram_count = 0;
    // Boot environment.
    MagickWandGenesis();
    // Allocate & read image
    wand = NewMagickWand();
    MagickReadImage(wand, "rose:");
    // Get Histogram as array of pixels
    histogram = MagickGetImageHistogram(wand, &histogram_count);
    // Iterate over each pixel & dump info.
    for (int i = 0; i < histogram_count; ++i)
    {
        printf("%s => %zu\n",
               PixelGetColorAsString(histogram[i]),
               PixelGetColorCount(histogram[i]));
    }
    // Clean-up
    histogram = DestroyPixelWands(histogram, histogram_count);
    wand = DestroyMagickWand(wand);
    MagickWandTerminus();
    return 0;
}

此示例将输出预期文本...

// ...
srgb(48,45,43) => 1
srgb(50,45,42) => 2
srgb(50,44,43) => 5
srgb(51,45,43) => 1
// ...

所以我猜你的 lua 脚本可能如下...

***image.lua***

local tlen = ffi.new("size_t[1]")
local t = lib.MagickGetImageHistogram(self.wand, tlen)
for i=0,tlen[0] do
    handle_new_pixel(self, t[i], lib.PixelGetColorCount(t[i]))
end
2017-03-29 13:10:53