xaxa
xaxa

Reputation: 1159

imagemagick Fill region outside of rectangle

I have an image and I want to fill with some color (e.g. blue) parts of that image which are outside of a rectangle. Position of left upper corner and width/height of this rectangle relative to the left upper corner of the original image are known.

enter image description here

Here borders of the original image are in red and borders of the rectangle are in black. Blue area should be filled.

How can I do this? I tried to create a tmp image and use a mask but it seems to also fill transparent regions inside the rectangle which is not what I want.

Also, there is probably a way to do it without creating intermediate images? I'd be interested in both options though, because I'm not sure how requirements will change over time -- maybe in the future I'd have to apply some other shape (not a rectangle), so having a way to apply an arbitrary mask would be better in that case.

Example:

Upvotes: 2

Views: 587

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207425

  • Find a colour that doesn't exist in the original image. Hint: use -unique-colors
  • Fill/draw the black image with that colour
  • Make everything that is not that colour blue. Hint: use -fill blue +opaque THATCOLOUR
  • The blue pixels are your mask

Not sure if I have understood you correctly, but here is what I get for the first part:

magick 7uZfM.png -alpha deactivate -fill yellow -draw "rectangle 117,-24 1117,1676" result1.png

enter image description here

And then the second part:

magick 7uZfM.png -alpha deactivate -fill yellow -draw "rectangle 117,-24 1117,1676" -fill blue +opaque yellow -transparent yellow result2.png

enter image description here

Ok, now with the original image showing through:

magick 7uZfM.png \( +clone -alpha deactivate -fill yellow -draw "rectangle 117,-24 1117,1676" -fill blue +opaque yellow -transparent yellow \) -flatten -background magenta result3.png

enter image description here

Upvotes: 3

Related Questions