5
$\begingroup$

I have picture with an irregular boundary. I draw line on it, but I want to omit the part of the line outside boundary. I have a rather primitive way of doing this with the following code. enter image description here

im=  https://i.sstatic.net/2fmSdwxM.png

fline[{x_, y_}] := If[PixelValue[im, {x, y}][[4]] == 1, Point[{x, y}]]
Graphics[{im, Line[{{175, 242}, {0, 50}}], Red,fline[{175, 242} - # {175, 192}/100]&/@ Range[100]}]

enter image description here

I would like to do this more efficiently, now I have to recalculate the line in Graphics to one according to the pixels of the image. Moreover, the picture will serve as a texture on which the line will be drawn, which is an added difficulty that I cannot solve.

$\endgroup$

3 Answers 3

9
$\begingroup$
im = Import["https://i.sstatic.net/2fmSdwxM.png"];

ColorReplace[
 ImageMultiply[AlphaChannel@ColorReplace[im, White -> Transparent], 
  Show[im, Graphics[{Red, InfiniteLine[{{0, 0}, {80, 110}}]}]]], 
 Black -> Transparent]

enter image description here

$\endgroup$
2
  • $\begingroup$ all useful solutions, thanks $\endgroup$ Commented Jun 28 at 14:45
  • 2
    $\begingroup$ @HansW. It would be kind to accept the answers. azerhajdan and cvgmt’s are excellent. $\endgroup$ Commented Jun 28 at 15:37
6
$\begingroup$

This works, but is it good enough for your purposes? Image->Binarize->Multiply->Fix up pixel colors

tmp = (*your original image*)

Binarize:

ColorNegate[Binarize[tmp]]

How did we do?

ImageMultiply[tmp, bi]

Adjust image sizes, get rid of plot margins, add graphics, and multiply

masked = 
 With[{im = 
    Image[Graphics[{tmp, Red, Line[{{349, 487}, {0, 50}}]}, 
      PlotRangePadding -> 0], ImageSize -> ImageDimensions[tmp]]},
  Graphics[ImageMultiply[
    im,
    bi], PlotRangePadding -> None, ImageMargins -> 0]

Fix the black and white pixels:

ColorReplace[masked, Black -> White]

enter image description here

$\endgroup$
1
  • $\begingroup$ If you want to automate finding the lines, ImageLines may work for you. Fiddling around with MorphologicalComponents may be useful too. $\endgroup$ Commented Jun 28 at 13:53
5
$\begingroup$
  • We could use ImageMesh.
Clear["Global`*"];
im = Import["https://i.sstatic.net/2fmSdwxM.png"];
reg = ImageMesh[ColorNegate@Binarize@im,Method -> "MarchingSquares"]

enter image description here

inner=BoundaryMeshRegion[MeshCoordinates[reg], 
 MeshCells[reg, 1, "Multicells" -> True][[2]]];
pt = RegionCentroid[inner];
dirs = RandomPoint[Circle[], 10];
Show[im, 
 ParametricPlot[Threaded@pt + t*dirs, {t, 0, EuclideanDistance @@ Transpose@RegionBounds[reg]}, 
  RegionFunction -> Function[{x, y}, RegionMember[reg, {x, y}]], 
  PlotStyle -> Directive@{Blue, Thick}]]

enter image description here

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.