Search code examples
pythonopencvnumpyimage-processing

convert image pixels from square to hexagonal


How can i convert the pixels of an image from square to hexagonal? Doing so i need to extract the rgb values from each hex pixel. Is there any library or function that simplify this process?

Example : Mona Lisa Hexagonal Pixel Shape

enter image description here Nothing tried. Thanks


Solution

  • Here's a possible approach, though I am sure if you are able to write code to read, manipulate and use pixels from a file format that hasn't been invented yet, you should be able to create that file yourself ;-)

    You could generate a hexagonal grid, using ImageMagick which is installed on most Linux distros and is available for OSX and Windows. Here, I am just doing things at the command-line in the Terminal, but there are Python, Perl, PHP, .Net, C/C++ and other bindings too - so take your pick.

    First make a grid of hexagons - you'll have to work out the size you need, mine is arbitrary:

    convert -size 512x256 pattern:hexagons hexagons.png
    

    enter image description here

    Now, fill in the hexagons, each with a different colour, I am just doing some examples of flood-filling here to give you the idea. Ideally, you would colour the first (top-left) hexagon with colour #000 and the next one across with #001 so that you could iterate through the coordinates of the output image as consecutive colours. Also, depending on your output image size, you may need to use a 32-bit PNG to accommodate the number of hexels (hexagonal pixels).

    convert hexagons.png                          \
       -fill red - draw "color 100,100 floodfill" \
       -fill blue -draw "color 200,200 floodfill" \
       colouredmask.png
    

    enter image description here

    Now iterate through all the colours, making every colour except that colour transparent. Note that I have added a black border just so you can see the context on StackOverflow's white background:

    convert colouredmask.png -fill none +opaque red onecell.png
    

    enter image description here

    Now mask the original image with that mask and get the average colour of that one cell and write it to your yet-to-be-invented file format. Repeat for all cells/colours.

    Note that the basic hexagon pattern is 30x18, so you should size your grid as multiples of that for it to tesselate properly.

    Note that if you have lots of these to process, you should consider using something like GNU Parallel to take advantage of multiple cores. So, if you make a script called ProcessOneImage and you have 2,000 images to do, you would use:

    parallel ProcessOneImage ::: *.png
    

    and it will keep, say 8, jobs running all the time if your PC has 8 cores. There are many more options, try man parallel.