0

I want to retrieve a list of n average colors in an image using Python Wand. From the command line, this can be achieved using Imagemagick directly.

convert image.jpg -colors $n -format %c histogram:info:-

Wands Image objects have a histogram dictionary, from which the list of colors can be accessed. But I cannot find a command to quantize the colors.

Can Wand perform color reduction? Is there a binding for -colors?

XZS
  • 2,124
  • 2
  • 16
  • 35

1 Answers1

2

I believe a Quantize image method is planned for future release. It might be worth checking out planned update branches on github. If you can't wait, and not comfortable working on development builds, you can access ImageMagick's C library directly through wand's API & ctypes.

from wand.image import Image
from wand.api import library
import ctypes

# Register C-type arguments
library.MagickQuantizeImage.argtypes = [ctypes.c_void_p,
                                        ctypes.c_size_t,
                                        ctypes.c_int,
                                        ctypes.c_size_t,
                                        ctypes.c_int,
                                        ctypes.c_int
                                       ]   
library.MagickQuantizeImage.restype = None

def MyColorRedection(img,color_count):
  '''
     Reduce image color count
  '''
  assert isinstance(img,Image)
  assert isinstance(color_count,int)
  colorspace = 1 # assuming RGB?
  treedepth = 8 
  dither = 1 # True
  merror = 0 # False
  library.MagickQuantizeImage(img.wand,color_count,colorspace,treedepth,dither,merror)

with Image(filename="image.jpg") as img:
  MyColorRedection(img,8) # "img' has now been reduced to 8 colors
emcconville
  • 20,969
  • 4
  • 43
  • 60