6
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

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["https://i.stack.imgur.com/wOPPys.png"];
i2 = Import["https://i.stack.imgur.com/KdDgSs.png"];
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

$\endgroup$
4
$\begingroup$
imgBlack=Import["https://i.stack.imgur.com/KdDgSs.png"];
imgRed=Import["https://i.stack.imgur.com/wOPPys.png"];
ImageCompose[imgRed,RemoveBackground[imgBlack]]  

enter image description here

$\endgroup$
4
$\begingroup$

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

Module[
 {img1, img2},
 {img1, img2} = Import /@ {
    "https://i.stack.imgur.com/KdDgSs.png",
    "https://i.stack.imgur.com/wOPPys.png"};
 ImageCompose[
  img2,
  RemoveBackground[img1, {White, 0.5}]]
 ]

Mathematica graphics

$\endgroup$
1
$\begingroup$

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

cover[imgBlackOnly,imgRedOnly]

$\endgroup$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.