Python-wand:如何读取图像属性/统计信息

0 投票
2 回答
1226 浏览
提问于 2025-04-27 22:38

我想从一张图片中提取一些统计数据,比如“平均值”、“标准差”等等。

不过,我在python-wand的文档里找不到相关的信息。

在命令行中,我可以这样获取这些统计数据:

convert MyImage.jpg -format '%[standard-deviation], %[mean], %[max], %[min]' info:

或者

convert MyImage.jpg -verbose info:

那么,如何在使用wand的Python程序中获取这些信息呢?

暂无标签

2 个回答

1

给跟随@emcconville这个很棒建议的朋友们提个醒:

  1. imagemagick网站上的文档是针对v7.x版本的。
  2. Wand只适用于imagemagick 6.x版本。
  3. 在IM6.x中,_ChannelStatistics的最后其实还有一个字段,叫做entropy(熵),它是一个双精度浮点数。如果你在ChannelStatistics的声明中漏掉这个字段,你的结构就会和返回的数据不对齐,结果会包含一堆无意义的东西。
2

目前, 这个库不支持 ImageMagick 的 C 语言接口中的任何统计方法(除了 直方图EXIF)。幸运的是,wand.api 提供了扩展功能的方式。

  1. 在 MagickWand 的文档中找到你需要的 方法
  2. 使用 ctypes 来实现数据类型和结构(可以参考 头文件 .h 的参考)。
from wand.api import library
import ctypes

class ChannelStatistics(ctypes.Structure):
    _fields_ = [('depth', ctypes.c_size_t),
                ('minima', ctypes.c_double),
                ('maxima', ctypes.c_double),
                ('sum', ctypes.c_double),
                ('sum_squared', ctypes.c_double),
                ('sum_cubed', ctypes.c_double),
                ('sum_fourth_power', ctypes.c_double),
                ('mean', ctypes.c_double),
                ('variance', ctypes.c_double),
                ('standard_deviation', ctypes.c_double),
                ('kurtosis', ctypes.c_double),
                ('skewness', ctypes.c_double)]

library.MagickGetImageChannelStatistics.argtypes = [ctypes.c_void_p]
library.MagickGetImageChannelStatistics.restype = ctypes.POINTER(ChannelStatistics)
  1. 扩展 wand.image.Image 类,并使用新支持的方法。
from wand.image import Image

class MyStatisticsImage(Image):
    def my_statistics(self):
        """Calculate & return tuple of stddev, mean, max, & min."""
        s = library.MagickGetImageChannelStatistics(self.wand)
        # See enum ChannelType in magick-type.h
        CompositeChannels = 0x002F
        return (s[CompositeChannels].standard_deviation,
                s[CompositeChannels].mean,
                s[CompositeChannels].maxima,
                s[CompositeChannels].minima)

撰写回答