Search code examples
colorsimagemagickaveragegraphicsmagick

ImageMagick - Find average color of a triangle in an image


This is a more advanced version of this question. From this image, how would I get the average color value of the pixels under the triangle from its co-ordinates with ImageMagick/GraphicsMagick/a different command-line tool? Preferably the solution should work for other polygons as well.


Solution

  • I ended up solving my problem by using the scikit-image and numpy python modules. Example code is as follows:

    from skimage import io, draw
    import numpy
    
    # read in the image as a numpy array
    image = io.imread("image.png")
    # setup a list of coords in the polygon
    polygon = numpy.array([[100, 100], [200, 100], [200, 200], [100, 200]])
    # Get a 2D list of pixels in the polygon
    pixels = image[draw.polygon(polygon[:, 1], polygon[:, 0])]
    # Use the channels of each pixel to get averages and convert them to ints
    channels = numpy.average(pixels, 0).astype(int)
    # Print!
    print(channels)