How to paste one image to another one, by forcing the former's background as transparent?

HMC 07/11/2018. 4 answers, 185 views
image-processing image

I have 2 images, imgBlackOnly and imgRedOnly as below, which already have the same ImageDimensions.

enter image description here

enter image description here

I want to paste imgBlackOnly to cover imgRedOnly, while the white part of imgBlackOnly is treated as "transparent" as what we did in the tiny software Paint of Windows. Thus my desired output is imgBlackCoverRed as below:

enter image description here

But one point to note is, the white part of imgBlackOnly is not totally white (since it is a screen capture from somewhere else), and therefore we need to force some "nearly white" part to be "totally white" by adding a manual threshold.

How can I do that? Many thanks!

To avoid misunderstanding, I also want to point out that the original picture of imgBlackOnly is not just black. It has several colors, with a "nearly white" background. Thanks.

4 Answers

C. E. 07/11/2018.

The definition of the function ColorReplace[img, color] is that it takes colors that are similar to (not exactly the same as) color and replaces those pixels with transparent pixels.

i1 = Import[""];
i2 = Import[""];
i1 = ColorReplace[i1, White];
i2 = ColorReplace[i2, White];
ImageCompose[i1, i2]

Mathematica graphics

You may notice that there are still some white pixels around the black figure. We can fix that by providing our own threshold for how far away a color can be from white and still be considered similar:

i2 = ColorReplace[i2, White, 0.5];
ImageCompose[i1, i2] 

Mathematica graphics

andre 07/11/2018.

enter image description here

rhermans 07/11/2018.

The threshold mentioned by @C.E. can also be used with RemoveBackground to remove the white edge.

 {img1, img2},
 {img1, img2} = Import /@ {
  RemoveBackground[img1, {White, 0.5}]]

Mathematica graphics

Fortsaint 07/12/2018.

cover=#2~ImageCompose~SetAlphaChannel[#1, ColorNegate@#1] &


Related questions

Hot questions


Popular Tags