Reputation: 345
I would like to us Magick++ or the imagemagick command line to extract an n-gon from an image. The n-gon is specified by a list the vertices. So, for example I would like to be able to extract an n-gon defined by the points a,b,c,d,e,f,g,h which define a region that looks like:
a---------h
| |
| g-f
| |
b---c |
| |
| |
| |
d-------e
out of, for example, a png image. I assume I have to do some kind of composite operation with an image mask, or if using Magick++ define a DrawableClipPath. But, I can't find any documentation for this. Any help would be appreciated.
p.s. My preference is to do this using C++ and Magick++ because I have other processing to do, but am happy to do it with the commandline too.
Upvotes: 3
Views: 1788
Reputation: 24419
You would use a combination of Magick::DrawablePolygon
and Magick::Image.composite
.
Create a new mask image, and draw the n-gon shape
Magick::Image mask;
mask.draw( Magick::DrawablePolygon( std::list<Magick::Coordinate> ) );
Then just apply the mask to a destination image, and compose the existing source.
Magick::Image dest;
dest.composite( Magick::Image, Magick::Geometry, Magick::CompositeOperator );
Example:
#include <iostream>
#include <Magick++.h>
int main(int argc, const char ** argv)
{
Magick::InitializeMagick(*argv);
Magick::Image mask( Magick::Geometry(120,120), Magick::Color("white"));
Magick::Image dest( Magick::Geometry(120,120), Magick::Color("white"));
// Example source image
Magick::Image source;
source.read("rose:");
source.resize(Magick::Geometry(200,120)); // Resize for fun
mask.fillColor("black");
// Define points
std::list<Magick::Coordinate> points;
points.push_back(Magick::Coordinate(10, 10)); // a
points.push_back(Magick::Coordinate(10, 50)); // b
points.push_back(Magick::Coordinate(30, 50)); // c
points.push_back(Magick::Coordinate(30,100)); // d
points.push_back(Magick::Coordinate(75,100)); // e
points.push_back(Magick::Coordinate(75, 30)); // f
points.push_back(Magick::Coordinate(60, 30)); // g
points.push_back(Magick::Coordinate(60, 10)); // h
// Draw Polygon "n-gon"
mask.draw( Magick::DrawablePolygon(points) );
// Extract n-gon from source image to destination image
dest.clipMask(mask);
Magick::Geometry offset(0,0,0,0);
dest.composite( source, offset, Magick::OverCompositeOp );
dest.write("n-gon.png"); // Output
}
Upvotes: 3