Adding contour to images – Mathematica Stack Exchange


Using ImageMesh and textures is a little more awkward than I expected it to be, but it does the job without needing image manipulation like EdgeDetect:

img = ImageCrop(Import("https://i.stack.imgur.com/PvtRV.png"));
mesh = ImageMesh(AlphaChannel(img));
coords = MeshCoordinates(mesh);
mmx = MinMax(coords((All, 1)));
mmy = MinMax(coords((All, 2)));
texcoords = {Rescale(#((1)), mmx), Rescale(#((2)), mmy)} & /@ coords;
g = Graphics({Thickness(.05), Line(coords), Texture(img), 
  Polygon(coords, VertexTextureCoordinates -> texcoords)})

with border

Hopefully the result is satisfactory. You can now rasterize it out using r = Rasterize(g, RasterSize -> ImageDimensions(img)). However you may notice it no longer lines up with the original if you do ImageCompose(img,{r,0.5}). That is due to some irritating quirk of ImageMesh and I have not figured out a work around yet.


Here’s how I managed it using image processing functions:

ImageCompose(
 img, (* t controls the thickness *)
 With({t = 5, dims = ImageDimensions(img)},
  Antialiasing ColorConvert(
    ColorNegate@
     ImageResize(
      ColorReplace(
       Dilation(EdgeDetect@ImagePad(AlphaChannel@img, t), t), 
       Black -> Transparent), dims), "RGB")
  )
 )

image padding