0

I am trying to extract statistics for an image such as the "mean", "standard-deviation" etc. However, I cannot find anything related in the python-wand documentation about it.

From the command line I can get such statistics like this:

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

or

convert MyImage.jpg -verbose info:

How to get such info from a python program using wand?

Vangelis Tasoulas
  • 3,109
  • 3
  • 23
  • 36

2 Answers2

2

Currently, doesn't support any of the statistic methods from ImageMagick's C-API (outside of histogram and EXIF). Luckily the wand.api is offered for extending functionality.

  1. Find the method you need in MagickWand's documentation.
  2. Use ctypes to implement data types/structures (reference header .h files)
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. Extend wand.image.Image, and use the newly supported methods.
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)
emcconville
  • 23,800
  • 4
  • 50
  • 66
1

Just a note to anyone following the excellent suggestion by @emcconville:

  1. The documentation on the imagemagick site is for v7.x
  2. Wand will only work with imagemagick 6.x
  3. In IM6.x, there is actually one more field on the end of _ChannelStatistics, a double called entropy, and if you leave it out of your ChannelStatistics declaration your structure won't align properly with what you get back and it'll contain a bunch of nonsense