Poisson image editing, and related techniques.
This page describes the Poisson image editing technique for blending two or more images. I implement the basic Poisson process as a fairly simple script, relaxFillMS.bat. However, this can be used in a number of ways.
This page is concerned with images, not mathematics. (I am a picture maker, not a mathematician.) Interested readers may feast on the mathematics in the references.
This page draws heavily on:
Other related papers, though not directly considered on this page:
We use two images from the following paper:
set BEAR=perez_bear.jpg 

set WATER=perez_water.jpg 
The images are not my copyright. I think the animal is a bear, but I could be wrong.
The goal is to cutout the bear and paste it over the water. The water in the foreground bear photo is generally darker than the required background.
For the cutout, we will use a mask that I made with Gimp, roughly following the example in the Pérez paper. It is white where we want the bear image; otherwise black.
set MASK=bear_mask.png 
We will offset the bear image:
set sOFFSET=+40+30 set sGEOM=geometry %sOFFSET%
Get the dimensions of the original bear image:
for /F "usebackq" %%L in (`%IM%identify ^ format "WW=%%w\nHH=%%h\nWm1=%%[fx:w1]\nHm1=%%[fx:h1]" ^ %BEAR%`) do set %%L echo WW=%WW% HH=%HH%
WW=297 HH=163
We can simply cut out the bear and composite over the water.
%IM%convert ^ %WATER% ^ ( %BEAR% %MASK% alpha off ^ compose CopyOpacity composite ^ ) ^ %sGEOM% ^ compose Over composite ^ spm_simpmont.jpg 
The boundary between the images is obvious. We want a seamless boundary. We could blur the boundary, but the difference in the water would still be obvious.
The basic method in the Pérez paper is called "Poisson interpolation", "seamless boundary by Poisson image editing" or even "seamless boundary by Poisson equation with Dirichlet boundary conditions". For short, I call it simply "Poisson pasting".
The simple version of the method (with no explicit "guidance vector field") adds an adjustment (or "correction") image to the foreground bear image before compositing it over the water background. The adjustment image has pixels corresponding to the mask boundary exactly equal to the water image minus the bear image. Hence, when added to the bear image, those pixels will be equal to the water background.
The pixels in the adjustment image outside the mask boundary won't be used so we don't care what values they have. The pixels inside the mask boundary do matter. Values should change smoothly, interpolating between values at the boundary. The smoother they change, the better the result. Put it another way: we should smooth the pixels of the adjustment image, and keep smoothing until they no longer change. This is exactly what relaxFillMS.bat does. (See Filling holes: relaxation.)
Calculate background minus foreground.
%IM%convert ^ %WATER% ^ %BEAR% ^ %sGEOM% ^ compose Mathematics ^ define compose:args=0,0.5,0.5,0.5 composite ^ crop %WW%x%HH%%sOFFSET% +repage ^ +depth ^ +write spm_minus.png ^ ( %MASK% negate ) ^ alpha off compose CopyOpacity composite ^ spm_minus_mskd.png 

Fill the hole by relaxation. call %PICTBAT%relaxFillMS ^ spm_minus_mskd.png . spm_add1.png 

Add the result to the bear image.
%IM%convert ^ %BEAR% ^ spm_add1.png ^ compose Mathematics ^ define compose:args=0,2,1,1 composite ^ +depth ^ +write spm_bear_adj.png ^ %MASK% alpha off ^ compose CopyOpacity composite ^ %WATER% ^ +swap ^ %sGEOM% ^ compose Over composite ^ spm_s2.png 
The result is good. We have the bear's reflection in the water, and the water's colour is taken from the correct image. Note that the water has lightened, but so has the bear. If we want to prevent the bear from becoming lightened, see Inner Dirichlet boundary below.
We can express the pixels that fill the hole as:
fill_pixels = bear + relax (water  bear)
At the boundary:
relax (water  bear) = water  bear
Hence, at the boundary:
fill_pixels = bear + water  bear = water
ASIDE
Instead of relaxFillMS.bat, we could use blurFill.bat. But this creates a discontinuity at the centre. For this example, the discontinuity is a roughly horizontal line that coincides with the base of the bear, so the problem it creates isn't visible.
call %PICTBAT%blurFill ^ spm_minus_mskd.png . spm_blr_add.png 
ASIDE 2
For the two mathematics composites, we could use compose:args=0,1,1,0.5 and compose:args=0,1,1,0.5 respectively. But if we don't use HDRI, this can clip the first result. The parameters used above have the same effect but ensure we have no clipping (at the expense of one bit of precision).
Above, we have adjusted the bear image to match the required background water. This has visibly lightened the bear's fur. Instead, we can adjust the water to match the bear.
%IM%convert ^ %WATER% ^ %BEAR% ^ %sGEOM% ^ compose Mathematics ^ define compose:args=0,0.5,0.5,0.5 composite ^ +depth ^ +write spm_minus_r.png ^ %MASK% ^ %sGEOM% ^ alpha off compose CopyOpacity composite ^ spm_minus_mskd_r.png 

call %PICTBAT%relaxFillMS ^ spm_minus_mskd_r.png . spm_add1_r.png 1e6 1000 

%IM%convert ^ %WATER% ^ spm_add1_r.png ^ compose Mathematics ^ define compose:args=0,2,1,1 composite ^ +depth ^ +write spm_bear_adj_r.png ^ ( %MASK% negate ) alpha off ^ %sGEOM% ^ set option:compose:outsideoverlay false ^ compose CopyOpacity composite ^ %BEAR% ^ %sGEOM% ^ compose DstOver composite ^ +depth ^ spm_s2_r.png 
So we can paste a foreground to a background with seamless boundary, either by adjusting the foreground or background. Of course, we could blend the two results.
The code above has used a boundary as exactly specified by a mask. Instead, a mask could define a range of possible boundaries, eg by describing a ring 20 pixels thick. Code could then find the darkest path around the ring, and we use that as the actual boundary.
%IM%convert ^ %MASK% ^ morphology EdgeOut disk:20 ^ spm_ring_mask.png 
We use shapeDp.bat to find the darkest path in the difference between the images, around this ring. (See Awkward boundaries with dark paths.) This needs two input images and the ring mask, all the same size.
%IM%convert ^ %WATER% ^ crop %WW%x%HH%%sOFFSET% +repage ^ spm_back_crp.png 

set sdpBLUR_SIG=0 set sdpMASK_FILE=spm_dp_mask.png call %PICTBAT%shapeDp ^ spm_back_crp.png %BEAR% spm_ring_mask.png 
shapeDp.bat outputs the second image composited over the first, via a calculated mask. We use that calculated mask.
set MASK2=spm_dp_mask.png %IM%convert ^ %WATER% ^ %BEAR% ^ %sGEOM% ^ compose Mathematics ^ define compose:args=0,0.5,0.5,0.5 composite ^ crop %WW%x%HH%%sOFFSET% +repage ^ +depth ^ +write spm_minus_rng.png ^ ( %MASK2% negate ) ^ alpha off compose CopyOpacity composite ^ spm_minus_mskd_rng.png 

call %PICTBAT%relaxFillMS ^ spm_minus_mskd_rng.png . spm_add1_rng.png 

%IM%convert ^ %BEAR% ^ spm_add1_rng.png ^ compose Mathematics ^ define compose:args=0,2,1,1 composite ^ +depth ^ +write spm_bear_adj_rng.png ^ %MASK2% alpha off ^ compose CopyOpacity composite ^ %WATER% ^ +swap ^ %sGEOM% ^ compose Over composite ^ +depth ^ spm_s2_rng.png 
The only noticable difference is that the water around the bear seems calmer. This is simply because the boundary is larger.
We implement the above in the script poissonPaste.bat. For simplicity, it requires the two input images and the mask to be the same size, with no offsets.
The script will adjust part of the second input image to match the first at the mask boundary. Using the mask, it then cuts out the second image and composites that over the first.
(Thus, for the common case where we adjust part of a small image to paste over a larger image, the relaxFillMS.bat wastes time blurring a large area that will be overwritten. The script could be optimised, eg by trimming the mask. Or we could have a wrapper that finds the trim of the mask, crops all three images to that, calls poissonPaste.bat, and finally reassembles the pieces.)
In this example, we extend the bear and mask to be the same size as the water.
%IM%convert ^ %WATER% ^ +depth ^ fill Black colorize 100 ^ ( clone 0 ^ %BEAR% ^ %sGEOM% ^ compose Over composite ^ +write spm_bear_ext.png ^ +delete ^ ) ^ ( clone 0 ^ %MASK% ^ %sGEOM% ^ compose Over composite ^ +write spm_mask_ext.png ^ +delete ^ ) ^ NULL: 
We can paste the bear over the water, or the water over the bear. The second image is adjusted to match the first, the "under" image, at the boundary and pasted over it.
Poissonpaste the bear over the water: call %PICTBAT%poissonPaste ^ %WATER% spm_bear_ext.png spm_mask_ext.png ^ spm_pp_out1.png 

Poissonpaste the water over the bear: call %PICTBAT%poissonPaste ^ spm_bear_ext.png %WATER% spm_mask_ext.png ^ spm_pp_out2.png 
In the next two examples, we negate the effect of the mask. As before, the second image is adjusted to match the first and pasted over it. But the adjustment and pasting is where the mask is black, instead of white.
Poissonpaste the bear under the water: call %PICTBAT%poissonPaste ^ %WATER% spm_bear_ext.png spm_mask_ext.png ^ spm_pp_out3.png 1 

Poissonpaste the water under the bear: call %PICTBAT%poissonPaste ^ spm_bear_ext.png %WATER% spm_mask_ext.png ^ spm_pp_out4.png 1 
An improved boundary for the Poisson pasting (relaxFillMs.bat) can be found by isolating the bear from its background.
Theorem: A 3D object with a constant colour, illuminated by white light, appears in a photograph to have varying lightness, somewhat varying saturation (or chroma), but constant hue.
Corollary: if we want to segment a photograph by objects, the hue channel is all we need.
In real life, objects rarely have exactly constant colour. And they are illuminated not merely by the main light source but also by light reflected by other objects, and this reflected light will be coloured. This is particularly evident when a lowsaturation (grayish) object is close to a highsaturation object (eg bright red). The gray object easily picks up red light from the reflected red object.
And objects that have very low saturation often have widely varying hues, eg a gray object may have adjacent pixels that are sRGB(50.001%,50%,50%) and sRGB(50%,50%,50.001%). This happens at the bear's nose, which is nearly black.
And reducing an image to just hues can cause objects that are clearly distinct to merge into each other.
But it is often a useful first approximation.
Here, we set the Lightness of all pixels to 50%. We could set all Chroma to 100%, but this gives false colours to pixels at the nose, so we set very low Chroma to zero, other Chroma to 100%, with a short ramp between them.
%IM%convert ^ %BEAR% ^ colorspace HCL ^ channel G level 3,5%% ^ channel B evaluate set 50%% ^ +channel ^ colorspace sRGB ^ spm_hue.png 
We want just two colours. In general, when we want just (N) colours, using "colors N" doesn't work well because many pixels we would want in in a particular group actually fall into the other. By using "colors N+x", virtually all the pixels allocated to one of the groups will be in the correct group. If N+x is too large, we fragment the natural groups too much that the next step won't work. N+2 often works well, when N is small.
%IM%convert ^ spm_hue.png ^ +dither colors 4 ^ spm_hue_4.png 
The sea has essentially two colours. Where the water is tilted up by a wave towards the camera, we see the colour of the water, which is somewhat green. Where the water is tilted away, the far side of a wave, we can't see into the water and instead see reflected light from the sky, which is more blue.
The sea also has a heavily distorted reflection and refraction of the bear. When reduced to four colours, a couple of small shapes have the bear's colour.
The script connCompLimArea.bat removes very small components (here, those that are less than 0.1% of the total image area).
call %PICTBAT%connCompLimArea ^ spm_hue_4.png spm_hue_4a.png 0.1c 
The script connCompLimNum.bat here limits the image to two components, mapping the other pixels to the colours of those two components. We have successfully lassooed the bear. Starting from the bear surrounded by water, we have found an outline for the bear.
call %PICTBAT%connCompLimNum ^ spm_hue_4a.png spm_hue_4a2.png 2 
(An alternative method for simplifying spm_hue_4.png is: find the unique colours in the four edges, remap the image to these; any pixels that have changed were a different colour to all edge pixels.)
Change the colours so we have a white background and black object.
%IM%convert ^ spm_hue_4a2.png ^ fill White ^ draw "color 0,0 floodfill" ^ fill Black +opaque White ^ spm_hue_bw.png 
Combine with the usersupplied mask:
%IM%convert ^ spm_hue_bw.png ^ %MASK% ^ compose Darken composite ^ spm_hue_bw2.png 
Now we have an outer and inner bound for a minimum error boundary cut (MEBC). The outer bound has been supplied by the user; the inner bound is from the lassoo. We find the optimum boundary within those limits.
set sdpBLUR_SIG=0 set sdpMASK_FILE=spm_dp_mask2.png call %PICTBAT%shapeDp ^ spm_back_crp.png %BEAR% spm_hue_bw2.png ^ spm_ring_mask2.png 
We can now use Poisson pasting with this mask.
Poissonpaste the bear over the water: %IM%convert ^ %WATER% ^ +depth ^ fill Black colorize 100 ^ spm_dp_mask2.png ^ %sGEOM% ^ compose Over composite ^ +write spm_mask2_ext.png call %PICTBAT%poissonPaste ^ %WATER% spm_bear_ext.png spm_mask2_ext.png ^ spm_pp_out5.png 
(Alternative: use Pp with spm_hue_bw.png, possibly dilated.)
See DragandDrop Pasting Jiaya Jia, Jian Sun, ChiKeung Tang, HeungYeung Shum, 2009.
poissonPaste.bat adjusts one image to match another at their boundary, by adding an adjustment image. The adjustment image is a relaxed ("membranised") version of the difference between the two input images. If the input images were identical at the boundary, the adjustment image would be zero at the boundary, so the relaxation would also be black and there would be no adjustment (nor any need for an adjustment). If the boundary pixels in the adjustment image were identical to each other, the relaxation would be a constant, flat colour, so the adjustment would be a constant colourshift.
We see this in the above example: the bear is lightened by the process.
Difficulties arise when one of the inputs contains detail (i.e. gradients) at the boundary that the other doesn't. This creates a variation in the boundary pixels of the adjustment image, and this variation is propagated somewhat into the adjustment, which causes localised colourshifts.
This isn't obvious in the above examples because both images have variation at the boundary, and the difference in the variation is of a similar magnitude. We can construct an artificial example:
%IM%convert ^ %BEAR% ^ crop 2x2@ ^ ( clone 0 fill White colorize 100 ) ^ delete 0 ^ ( clone 0 fill Lime colorize 100 ) ^ delete 0 ^ ( clone 0 fill Red colorize 100 ) ^ delete 0 ^ ( clone 0 fill Black colorize 100 ) ^ delete 0 ^ layers merge ^ spm_chq.png 

call %PICTBAT%poissonPaste ^ spm_chq.png %BEAR% %MASK% ^ spm_chq_out.png 
The four background colours have clearly propagated into the bear. In this example, no alternative boundary is available, so we can't avoid the effect.
When we have a choice of boundaries, represented in examples above by a white ring, we have chosen the path that minimises the total difference between the input images.
Instead, we can choose the path that minimises the difference in the slopes (a.k.a. gradients; see the Slopes page) of the inputs. For both inputs, we calculate the slopes and record x and ydeltas for each colour channel in two images (because we need six channels). For each channel we then calculate the difference between the slopes, and use the maximum magnitude of these as the input to the darkestpntpnt process module.
(Instead of using six channels, we could instead use the slopes of the grayscaled images, needing just two channels.)
For the slope*.bat scripts, see the Slopes page.
Below, "sigmoidalcontrast" and "autolevel" are merely to aid visibility.
Get the slope of the bear image. call %PICTBAT%slopeXY ^ %BEAR% spm_bear_slp.miff %IM%convert spm_bear_slp.miff[0] ^ sigmoidalcontrast 10,50%% ^ spm_bear_slp_0.jpg %IM%convert spm_bear_slp.miff[1] ^ sigmoidalcontrast 10,50%% ^ spm_bear_slp_1.jpg 

Get the slope of the water image. call %PICTBAT%slopeXY ^ spm_back_crp.png spm_water_slp.miff %IM%convert spm_water_slp.miff[0] ^ sigmoidalcontrast 10,50%% ^ spm_water_slp_0.jpg %IM%convert spm_water_slp.miff[1] ^ sigmoidalcontrast 10,50%% ^ spm_water_slp_1.jpg 

Subtract: slope(water)  slope(bear) call %PICTBAT%slopeXYminus ^ spm_bear_slp.miff spm_water_slp.miff ^ spm_minus_slp.miff %IM%convert spm_minus_slp.miff[0] ^ sigmoidalcontrast 10,50%% ^ spm_minus_slp_0.jpg %IM%convert spm_minus_slp.miff[1] ^ sigmoidalcontrast 10,50%% ^ spm_minus_slp_1.jpg 

Get the magnitude of the slope difference. call %PICTBAT%slopeXYmag ^ spm_minus_slp.miff ^ spm_mag_slp.miff %IM%convert spm_mag_slp.miff ^ autolevel ^ spm_mag_slp.jpg 

Find the line of minimum total magnitude within the ring. call %PICTBAT%minDp ^ spm_mag_slp.miff spm_hue_bw2.png ^ spm_mag_msk.png 

Poissonpaste. call %PICTBAT%poissonPaste ^ spm_back_crp.png %BEAR% spm_mag_msk.png ^ spm_mag_out.png 
In some ways, this result is more accurate than previous results, creating less bleeding of features from the background to the new foreground. However, the boundary in this example is also tighter, closer to the bear. We no longer have the bear's reflection in the water.
Ordinary (nonguided) Poisson Image Editing creates a result that has a gradient very close to g, the required foreground ("source"). The result is made by adding a membrane to the foreground, where the membrane was made by relaxing a boundary of (background minus foreground).
Guided Poisson Image Editing creates a result that has a gradient very close to v, called a "guidance vector field". v is set to some function of g and f* (the original background). The result is made from the membrane itself, not added to anything, and the membrane is made by relaxing a boundary of simply the background. But the method of relaxation is more complicated.
The guidance vector field might come from the gradient of a single image, or from a mixture of gradients of different images (aka mixed gradients).
Below, slp_ws_div.miff is the right hand side of the equation:
f(x1,y) + f(x+1,y) + f(x,y1) + f(x,y+1)  4*f(x,y) = rhs(x,y)
So each iteration is:
f(x,y) = f(x1,y) + f(x+1,y) + f(x,y1) + f(x,y+1)  rhs(x,y) 4 4
In IM terms: convolve once, subtract something, convolve again, subtract the same thing, and keep going.
For example, we take two other images from the Pérez paper:
A scribble image. set SCRIBBLE=perez_scribble.jpg 

A wall image, cropped to the same size as the scribble. %IM%convert ^ %SCRIBBLE% ^ perez_wall.jpg ^ compose Over composite ^ spm_wall_crp.png set WALL=spm_wall_crp.png 

Make a mask in Gimp, roughly the same as the Pérez paper. set WS_MASK=perez_ws_mask.png 
For the result: where the mask is black, we want the wall. Where the mask is white, we want the gradient of either the wall or the scribble, whichever is more significant at that pixel.
To do that, we find the gradients (on x and y directions) of both images; find the magitudes of each gradient; find which magnitude is greater; for each pixel, use the slope of the image with the greatest magnitude; find the divergence of that.
Slope of the scribble. call %PICTBAT%slopeXY ^ %SCRIBBLE% slp_scrb_sxy.miff %IM%convert slp_scrb_sxy.miff[0] slp_scrb_sxy_0.png %IM%convert slp_scrb_sxy.miff[1] slp_scrb_sxy_1.png 

Slope of the wall. call %PICTBAT%slopeXY ^ %WALL% slp_wall_sxy.miff %IM%convert slp_wall_sxy.miff[0] slp_wall_sxy_0.png %IM%convert slp_wall_sxy.miff[1] slp_wall_sxy_1.png 

Magnitude of the scribble slope. call %PICTBAT%slopeXYmag ^ slp_scrb_sxy.miff slp_scrb_mag.miff 

Magnitude of the wall slope. call %PICTBAT%slopeXYmag ^ slp_wall_sxy.miff slp_wall_mag.miff 

Which magnitude is greatest? White for scribble, black for wall. %IM%convert ^ slp_wall_mag.miff slp_scrb_mag.miff ^ colorspace Gray ^ compose MinusDst composite ^ fill White +opaque Black ^ slp_ws_mag_diff.png 

Use the slope that has the greatest magnitude. rem FIXME: Can't use mpr?? %IM%convert ^ ( slp_wall_sxy.miff[0] ^ slp_scrb_sxy.miff[0] ^ slp_ws_mag_diff.png +write mpr:MSK ^ alpha off ^ compose Over composite ^ ) ^ ( slp_wall_sxy.miff[1] ^ slp_scrb_sxy.miff[1] ^ slp_ws_mag_diff.png ^ alpha off ^ compose Over composite ^ ) ^ slp_ws_mxslp.miff %IM%convert slp_ws_mxslp.miff[0] slp_ws_mxslp_0.png %IM%convert slp_ws_mxslp.miff[1] slp_ws_mxslp_1.png 

Find the divergence. call %PICTBAT%slopeXYdiv ^ slp_ws_mxslp.miff slp_ws_div.miff This will be subtracted after each blur. 
This divergence is the required slope of the slope of the result.
With the mask, make a hole in the wall. %IM%convert ^ %WALL% ^ ( %WS_MASK% negate ) ^ alpha off ^ set option:compose:outsideoverlay false ^ compose CopyOpacity composite ^ slp_wall_msk.miff 
We relaxfill the hole, using the divergence as the guidance field.
call %PICTBAT%relaxFillMS ^ slp_wall_msk.miff . slp_wall_msk_rfs2.miff ^ 0.0001 1000 . slp_ws_div.miff 0 00:06:17 
This is essentially the same result as in the Pérez paper. The blue scribble has become purple, i.e. it has increased in redness. This is because the wall is redder than the scribble, at the boundary.
Other results:
Make a gray image, and holed gray image. %IM%convert ^ %WALL% ^ alpha off ^ fill gray(50%%) colorize 100 ^ +depth ^ +write slp_ws_gray.png ^ ( %WS_MASK% negate ) ^ alpha off compose CopyOpacity composite ^ slp_ws_gray_m.png 

Relax the holed wall. call %PICTBAT%relaxFillMS ^ slp_wall_msk.miff . slp_wall_msk_rf.miff 

Relax the holed wall, guided by gray(50%), ie zero. call %PICTBAT%relaxFillScr ^ slp_wall_msk.miff . slp_wall_msk_gr_rfs.miff ^ 0.001 100 . slp_ws_gray.png The result is the same (but slower). 

Relax the holed gray(50%), guided by the divergence. call %PICTBAT%relaxFillScr ^ slp_ws_gray_m.png . slp_gray_rfs.miff ^ 0.001 100 . slp_ws_div.miff 

Poissonpaste, with userdefined mask. call %PICTBAT%poissonPaste ^ %WALL% %SCRIBBLE% perez_ws_mask.png ^ spm_ws_out2.png 

Poissonpaste, with maxmagnitude mask. call %PICTBAT%poissonPaste ^ %WALL% %SCRIBBLE% slp_ws_mag_diff.png ^ spm_ws_out4.png 
Another image from the Pérez paper. %IM%convert ^ perez_flower.jpg ^ crop 350x350+0+0 +repage ^ spm_flower.png set FLOWER=spm_flower.png 

A loose mask, made in Gimp. set FLR_MASK=flower_mask.png 
The mask is very loose, entirely surrounding the flower; we haven't bothered to try and capture just the tendrils.
The goal is to make the background (the nonflower) monochrome, without changing the flower.
Gray version of flower. %IM%convert ^ %FLOWER% ^ colorspace Gray ^ +depth ^ spm_flr_gr.png 

Gray version, with hole. %IM%convert ^ spm_flr_gr.png ^ ( %FLR_MASK% negate ) ^ alpha off ^ compose CopyOpacity composite ^ spm_flr_gr_h.png 

Slope of colour flower. call %PICTBAT%slopeXY ^ %FLOWER% spm_flr_sxy.miff %IM%convert spm_flr_sxy.miff[0] spm_flr_sxy_0.png %IM%convert spm_flr_sxy.miff[1] spm_flr_sxy_1.png 

Divergence of slope of flower. call %PICTBAT%slopeXYdiv ^ spm_flr_sxy.miff spm_flr_div.png We will use this as the guidance field. 

Relaxfill the holed grayscale version, with guidance. call %PICTBAT%relaxFillMS ^ spm_flr_gr_h.png . spm_flr_bwc.png ^ 0.0001 1000 . spm_flr_div.png A good result, but the entire flower has become slightly gray. 
This is essentially the same result as shown in the Pérez paper.
If the result seems too good to be true, well, it is.
Where the mask is black, the result is grayscale, of course. Where the mask is white, the result is the colour input with green "subtracted" (speaking approximately). So the flower has become less green: values in the green channel have decreased, while values in the red and blue channels have increased. This has happened beacause that is the change at the boundary. Similarly, yellow colour has leached out from the flower to the grayscale areas between the tendrils. This is addressed in Inner Dirichlet boundary below.
The guidance field might be from the background image, but modulated in some way.
Yet another image from the Pérez paper:
set BOY=perez_boy.jpg 

With Gimp, make a mask that includes just the facial features. set BOY_MASK=boy_mask.png 

Get the slope of BOY. call %PICTBAT%slopeXY ^ %BOY% spm_boy_sxy.miff Modify the slope. %IM%convert ^ spm_boy_sxy.miff ^ fuzz 2%% fill gray(50%%) opaque gray(50%%) ^ level 10%%,90%% ^ spm_boy_sxy2.miff Get the divergence of the modified slope. call %PICTBAT%slopeXYdiv ^ spm_boy_sxy2.miff spm_boy_div2.png 

Poissonpaste. call %PICTBAT%poissonPaste ^ %BOY% . %BOY_MASK% ^ spm_boy_out2.png ^ . spm_boy_div2.png 
We have adjusted the slope so where it is within ±2% of 50% (i.e. zero), it becomes 50%. This eliminates small slopes. It has a sideeffect of reducing overall contrast, because slope accumulates to make contrast, so we compensate very approximately with a "level", but this is a kludge. Instead, we could match the result to the input image, using either imgGainBias.bat or matchHisto.bat. Another option would be to match the adjusted slope to the nonadjusted slope.
In the next example, after eliminating small slopes, we sharpen the remaining slopes. This increases local contrast.
Modify the slope. %IM%convert ^ spm_boy_sxy.miff ^ fuzz 2%% fill gray(50%%) opaque gray(50%%) ^ level 10%%,90%% ^ unsharp 0x3+1+0 ^ spm_boy_sxy3.miff Get the divergence of the modified slope. call %PICTBAT%slopeXYdiv ^ spm_boy_sxy3.miff spm_boy_div3.png 

Poissonpaste. call %PICTBAT%poissonPaste ^ %BOY% . %BOY_MASK% ^ spm_boy_out3.png ^ . spm_boy_div3.png 
A different effect is obtained by increasing the contrast of divergence, around the 50% level. This changes the slope of the slope of the result (increasing overall contrast), so a small change here goes a long way.
%IM%convert ^ spm_boy_div2.png ^ sigmoidalcontrast 3,50%% ^ spm_boy_div4.png 

Poissonpaste. call %PICTBAT%poissonPaste ^ %BOY% . %BOY_MASK% ^ spm_boy_out4.png ^ . spm_boy_div4.png 
More generally, poissonPaste.bat gives us a method of modifying the pixels in part of an image and blending the modified part into the original; an alternative to alpha blending.
See Image Editing without Color Inconsistency Using Modified Poisson Equation, Qin Chuan, Wang Shuozhong, Zhang Xinpeng, 2008.
In examples above, the colour difference at the boundary has influenced all result pixels inside the boundary, so the bear has become lightened, the scribble has become purple, and the flower has become less green. This is also known as "colour inconsistency" or "colour contamination". Sometimes we want this effect, but sometimes we don't.
The pixels to be filled already have an outer boundary condition, where the adjustment to be added is "water" minus "bear", so when this is added to "bear" the result at the outer boundary is "water". Chuan et al suggest we add an additional condition at the bear pixels, setting the adjustment to be added to "zero", so when this is added to "bear" the result at the inner boundary is "bear".
The script poissonPasteIDB.bat takes two masks, one for each of the outer and inner boundaries. The inner boundary mask is white where we want the bear unchanged, and black elsewhere.
Chuan et al suggest the user should create the bear mask. But we have created one automatically, so we can use that. We shrink spm_hue_bw.png by a few pixels. Black now has pixels that are in the bear. Add this to MASK, so now we have a white ring that is to be solved by Poisson equation.
The two masks together form what is often called a trimap; a map that labels some pixels as certainly inside the object, some as certainly outside, and others as unknown.
poissonPasteIDB does the following for nonguided Poissonpasting:
For guided pating, poissonPasteIDB does the following:
As a happy sideeffect: the area to be filled is now the ring between the outer and inner masks. This ring shape is smaller than before, so fewer pixels need filling by relaxFillMS.bat, so this is faster than without an inner mask.
Create the inner boundary mask. %IM%convert ^ spm_hue_bw.png ^ morphology Dilate disk:3 ^ negate ^ spm_bear_sm.png 

call %PICTBAT%poissonPasteIDB ^ spm_back_crp.png %BEAR% ^ %MASK% spm_bear_sm.png ^ spm_idb_out.png 

Another example:
call %PICTBAT%poissonPasteIDB ^ spm_chq.png %BEAR% ^ %MASK% spm_bear_sm.png ^ spm_idb_out2.png 
The result has pixels at the outer boundary the same colour as the background, and pixels at the inner boundary the same colour as the bear. Hence we now have colour consistency.
We can do the same trick with the flower.
Create the inner boundary mask with Gimp. set FLR_IN_MASK=flower_inner_mask.png 

Check the masks. %IM%convert ^ %FLR_MASK% ^ ( %FLR_IN_MASK% negate ) ^ compose Darken composite ^ %FLOWER% ^ +swap ^ alpha off ^ compose CopyOpacity composite ^ alpha Background ^ +depth ^ spm_flr_chk.png 

Poissonpaste the grayscale version. call %PICTBAT%poissonPasteIDB ^ spm_flr_gr.png %FLOWER% ^ %FLR_MASK% %FLR_IN_MASK% ^ spm_flr_bwc3.png The tendrils have lost some colour, become whiter. 

Poissonpaste the grayscale version, with guidance. call %PICTBAT%poissonPasteIDB ^ spm_flr_gr.png %FLOWER% ^ %FLR_MASK% %FLR_IN_MASK% ^ spm_flr_bwc4.png ^ . spm_flr_div.png The tendrils are a good colour, but have slightly blurred. 
However, the tendrils have become somewhat gray and the monochrome areas between tendrils have become somewhat yellow. Chuan et al suggest a solution. In the guidance field, where the pixels represent either the yellow flower or the grayscale background, the values are low (i.e. close to zero). At the border between the flower and background, the gradient field has relatively high values (i.e. distant from zero). If we make the high values even higher, we will get a steeper gradient between the two, so less colour bleed. Where the gradient field is above a certain threshold, they increase the values by a certain factor. For the threshold, they use 80% of the maximum value M. For the factor, they use K. They calculate:
ForeIn: mean of foreground at the inner boundary
ForeOut: mean of foreground at the outer boundary
BackOut: mean of background at the outer boundary
K = ForeIn  BackOut ForeIn  ForeOut M = max(guidance_field)
I suppose the same multiplier is applied to all three channels. But what if K less than one? Less than zero?
More simply, we can sharpen the guidance field:
Sharpen the guidance. %IM%convert ^ spm_flr_div.png ^ unsharp 0x0.5+1+0.05 ^ spm_flr_div_u.png 

Poissonpaste the grayscale version, with sharpened guidance. call %PICTBAT%poissonPasteIDB ^ spm_flr_gr.png %FLOWER% ^ %FLR_MASK% %FLR_IN_MASK% ^ spm_flr_bwc5.png ^ . spm_flr_div_u.png This has reduced the bleed of yellow into the monochrome,

We can restore the sharpness with a small "unsharp" applied just in the transition area, between the two masks:
%IM%convert ^ spm_flr_bwc4.png ^ ( +clone unsharp 0x0.5+1+0 ) ^ ( %FLR_IN_MASK% negate ^ %FLR_MASK% ^ compose Darken composite ^ ) ^ compose Over composite ^ spm_flr_bwc4_u.png 
Above, we have seen that colourchange at the boundary is propagated inwards, creating a colour cast. We have seen this can be prevented by an inner Dirichlet boundary. On the other hand, we can use this to our advantage.
Poisson pasting can be used to correct colours when photographs are to be joined with overlaps ("stitched"), such as panoramas or aerial photography. Suppose we have these three input images:
#1: %IM%convert ^ size 150x100 xc: ^ sparsecolor bilinear ^ 0,0,#67f,0,%%[fx:h1],#6f7,%%[fx:w1],0,#45d ^ gravity Center pointsize 30 ^ fill Black annotate +0+0 "#1" ^ fill White annotate 22 "#1" ^ spm_pan_in1.png 

#2: %IM%convert ^ size 150x100 xc: ^ sparsecolor bilinear ^ 0,0,#f88,0,%%[fx:h1],#7f6,%%[fx:w1],0,#faa ^ fill White gravity Center pointsize 30 ^ fill Black annotate +0+0 "#2" ^ fill White annotate 22 "#2" ^ spm_pan_in2.png 

#3: %IM%convert ^ size 150x100 xc: ^ sparsecolor bilinear ^ 0,0,#a6f,0,%%[fx:h1],#8d7,%%[fx:w1],0,#c7f ^ fill White gravity Center pointsize 30 ^ fill Black annotate +0+0 "#3" ^ fill White annotate 22 "#3" ^ spm_pan_in3.png 
Suppose they should overlap like this:
set OFFS_2=+130+10 set OFFS_3=+25010 %IM%convert ^ spm_pan_in1.png ^ ( spm_pan_in2.png repage %OFFS_2% ) ^ ( spm_pan_in3.png repage %OFFS_3% ) ^ background None ^ layers merge +repage ^ spm_pan_out1.png set CROP_2=150x100%OFFS_2% 
There are many possible ways to blend these images, including:
We will use the third way.
The boundary condition, where we require the images to match, are at most of the left edge of #2 and part of the top (an inverted "L"), and an "L" shape near the right edge of #2.
We make a mask of the "L" shapes. The following is messy but depends only on the image sizes, their order, and the "repage" arguments. "fuzz" is used in case twice gray(50%) isn't exactly white. "layers merge" puts offsets in the output, in this case +010, so we can later use #2 offsets directly for cropping.
%IM%convert ^ size 150x100 ^ xc:gray(50%%) ^ fuzz 0.1%% ^ ( xc:Red ^ shave 1x1 bordercolor gray(50%%) border 1 ^ repage %OFFS_2% ^ ) ^ background Black ^ compose Plus layers merge +repage ^ fill gray(50%%) opaque Red ^ ( xc:Red ^ shave 1x1 bordercolor gray(50%%) border 1 ^ repage %OFFS_3% ^ ) ^ background Black ^ compose Plus layers merge ^ fill Black +opaque White ^ spm_Lboth.png Note: the output has offsets. 

Crop to #2: %IM%convert ^ spm_Lboth.png ^ crop %CROP_2% +repage ^ spm_L_cr.png 
We use this to blend image #2 with the other two images.
Subtract #2 from the others: %IM%convert ^ spm_pan_in1.png ^ ( spm_pan_in3.png repage %OFFS_3% ) ^ background None ^ layers merge ^ ( spm_pan_in2.png repage %OFFS_2% ) ^ compose Mathematics ^ define compose:args=0,0.5,0.5,0.5 ^ layers merge ^ spm_pan_sub.png Note: output has offsets. 

Crop to #2: %IM%convert ^ spm_pan_sub.png ^ crop %CROP_2% +repage ^ spm_pan_sub_cr.png 

Mask by the Lshapes: %IM%convert ^ spm_pan_sub_cr.png ^ spm_L_cr.png ^ compose CopyOpacity composite ^ spm_pan_sub_lcr.png 

Relaxfill to get an adjustment image: call %PICTBAT%relaxFillMS ^ spm_pan_sub_lcr.png . spm_pan_rf.png ^ 1e6 1000 

Add the adjustment image to #2: %IM%convert ^ spm_pan_in2.png ^ spm_pan_rf.png ^ compose Mathematics ^ define compose:args=0,2,1,1 composite ^ spm_pan_2adj.png 

Paste: %IM%convert ^ spm_pan_in1.png ^ ( spm_pan_2adj.png repage %OFFS_2% ) ^ ( spm_pan_in3.png repage %OFFS_3% ) ^ background None ^ layers merge +repage ^ spm_pan_123.png 
As required, the images blend seamlessly. Image #2 has been adjusted to exactly match two adjacent images. If image #2 had been entirely surrounded by other images, similar processing could be done.
We can readily add further conditions. For example, we might want the central column of image #2 to be unchanged. This needs gray(50%) in the adjustment image.
Add a gray line: %IM%convert ^ spm_pan_sub_lcr.png ^ stroke gray(50%%) ^ draw "line 75,0,75,99" ^ spm_pan_sub_lcr2.png 

Relaxfill to get an adjustment image: call %PICTBAT%relaxFillMS ^ spm_pan_sub_lcr2.png . spm_pan_rf2.png ^ 1e6 1000 

Add the adjustment image to #2: %IM%convert ^ spm_pan_in2.png ^ spm_pan_rf2.png ^ compose Mathematics ^ define compose:args=0,2,1,1 composite ^ spm_pan_2adj2.png 

Paste: %IM%convert ^ spm_pan_in1.png ^ ( spm_pan_2adj2.png repage %OFFS_2% ) ^ ( spm_pan_in3.png repage %OFFS_3% ) ^ background None ^ layers merge +repage ^ spm_pan_1232.png 
The various technical papers (Pérez etc) describe the mathematics of Poisson image editing. Here is a lessmathematical explanation. The goal is to create an image where some pixels have desired values (the boundary contraint) while others are such that the slope either changes as slowly as possible, or the rate of change follows a guidance.
The script relaxFill.bat aims at a zero rate of change of gradient.
At each iteration, for every pixel (and every channel), we set the new pixel value to the average value of the four neighbours to the north, south, east and west. This is a blurring operation. If we repeat this often enough, every pixel will be almost equal to the average of the four neighbours. This means the slope (gradient) of the image will be almost the same everywhere. It doesn't change quickly. Put it another way, the slope of the slope (the "second derivative") will be almost zero.
Generally, pixels won't be exactly equal to the average of the neighbours. That happens only when the result is a bilinear gradient, which only happens when the boundary values when considered as heights are coplanar. But the repeated iteration gets the overall image as close to this result as it can get.
A bit of maths (sorry): if we say that each pixel value is a function of x and y, the pixel is f(x,y), then the following is approximately true for every pixel in the relaxed result:
f(x1,y) + f(x+1,y) + f(x,y1) + f(x,y+1)  4*f(x,y) = 0
The left hand side of that equation approximates the slope of the slope of the image.
To get to that state, each iteration sets a new value for each pixel f'(x,y):
f'(x,y) = f(x1,y) + f(x+1,y) + f(x,y1) + f(x,y+1) 4
In ImageMagick code, this is:
morphology convolve:n 3x3:0,0.25,0,0.25,0,0.25,0,0.25,0
... where n is however many iterations we want to make between each test for completion.
The iterative process has to start somewhere. We need an initial guess at the result, and each iteration takes us closer to the actual result. With luck there is no local minimum so the initial guess doesn't matter; any initial guess will eventually give us the same result. But the closer the initial result is to the actual result, the quicker we will get there.
The relaxFillScr.bat is a little more complex. Instead of aiming to set the slope of the slope to zero for every pixel, it aims at some other particular slope of the slope for each pixel. The values to be aimed at are given in the guidance image. So in the relaxed result, the following is approximately true:
f(x1,y) + f(x+1,y) + f(x,y1) + f(x,y+1)  4*f(x,y) = guide(x,y)
So each iteration is:
f'(x,y) = f(x1,y) + f(x+1,y) + f(x,y1) + f(x,y+1)  guide(x,y) 4 4
IM can't do this in a single operation. (For example, morphology can't use more than one image as input.) So each iteration has two phases: first we convolve as above, then we subtract another image. These phases fight each other: we smooth then roughen the image, and repeat this smoothing and roughening. This makes the process slow to converge.
In preparation for the script, we set the guidance image to the divergence of the required gradient, so it is the sum of the slope of the slope in the x and y directions.
Divergence can be negative, so we offset this for IM by 50% in the usual way so gray(50%) represents zero divergence.
This calls either relaxFill.bat or relaxFillScr.bat at multiple scales. For relaxFill.bat, this always improves performance. However, for relaxFillScr.bat the improvement may be small or even negative.
Here is a simple example of relaxation with no explicit guidance:
Paste: %IM%convert ^ size 400x300 xc:None ^ size 20x300 ^ xc:#f80 gravity West composite ^ xc:#ff0 gravity East composite ^ size 400x20 ^ xc:#08f gravity North composite ^ xc:#080 gravity South composite ^ spm_bnd.png 

Paste: call %PICTBAT%relaxFillMS ^ spm_bnd.png . spm_bnd_rf.png 
This is a higherlevel script. For inputs it uses a background, foreground and mask. The mask should be white where we want the adjusted foreground, and hence defines the area that will be relaxed.
The script optionally takes a guidance image.
This is like poissonPaste.bat, but takes an extra mask, that is white where we want the foreground to be unchanged. Hence the area to be relaxed is between the two masks.
If it is called with this inner mask set to dot, ".", it instead calls poissonPaste.bat.
To further illustrate the relaxation process, we make a simple example, and show the intensity graphs at a crosssection through the images, at the middle row.
Create a background. %IM%convert ^ size 200x200 gradient: ^ rotate 90 ^ spm_xb.png call %PICTBAT%xSection spm_xb.png 

Create a foreground. The square is 40% lighter than its surround. %IM%convert ^ size 200x200 xc:gray(30%%) ^ fill gray(70%%) draw "rectangle 80,80 120,120" ^ spm_xf.png call %PICTBAT%xSection spm_xf.png 

Create a mask. %IM%convert ^ size 200x200 xc:Black ^ fill White draw "circle 100,100 150,100" ^ spm_xm.png 
The goal is to blend the background and foreground, where the mask is white.
We show the elapsed time for the process, and the number of iterations.
Poisson paste with minimal iterations. set rfCOMP_METRIC=PAE set ppTGT_SCORE=999 set ppNUM_STEPS=1 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout1.png call %PICTBAT%xSection spm_xout1.png 0 00:00:02 rfmsITER=2 

Poisson paste. set rfCOMP_METRIC=PAE set ppTGT_SCORE=0.1 set ppNUM_STEPS=10 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout2.png call %PICTBAT%xSection spm_xout2.png 0 00:00:01 rfmsITER=20 

Poisson paste to approximate completion. set rfCOMP_METRIC=PAE set ppTGT_SCORE=0.001 set ppNUM_STEPS=1000 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout3.png call %PICTBAT%xSection spm_xout3.png 0 00:00:12 rfmsITER=5000 In the finished result, the square is 40% lighter than its surround. 
We will repeat the above, but with an explicit guidance field. First, we make a guidance field: the divergence of the slope of the foreground.
call %PICTBAT%slopeXY spm_xf.png spm_xf_sxy.miff call %PICTBAT%slopeXYdiv spm_xf_sxy.miff spm_xf_div.png call %PICTBAT%xSection spm_xf_div.png 
Now we use this divergence as the guidance:
Poisson paste with minimal iterations. set rfCOMP_METRIC=PAE set ppTGT_SCORE=999 set ppNUM_STEPS=1 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout1g.png . spm_xf_div.png call %PICTBAT%xSection spm_xout1g.png 0 00:00:01 rfmsITER=2 

Poisson paste. set rfCOMP_METRIC=PAE set ppTGT_SCORE=0.1 set ppNUM_STEPS=10 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout2g.png . spm_xf_div.png call %PICTBAT%xSection spm_xout2g.png 0 00:00:02 rfmsITER=30 

Poisson paste to approximate completion. set rfCOMP_METRIC=PAE set ppTGT_SCORE=0.001 set ppNUM_STEPS=1000 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout3g.png . spm_xf_div.png call %PICTBAT%xSection spm_xout3g.png 0 00:01:19 rfmsITER=10000 
Using an explicit guidance field of the divergence of the slope of the foreground eventually gives almost the same result as using no explicit guidance field. But it takes eight times as long.
We can use a sharper divergence:
call %PICTBAT%shpDiv spm_xf.png spm_xf_div2.png call %PICTBAT%xSection spm_xf_div2.png 

Poisson paste. set rfCOMP_METRIC=PAE set ppTGT_SCORE=0.001 set ppNUM_STEPS=1000 call %PICTBAT%poissonPaste ^ spm_xb.png spm_xf.png spm_xm.png ^ spm_xout3g2.png . spm_xf_div2.png call %PICTBAT%xSection spm_xout3g2.png 0 00:01:07 rfmsITER=8000 
There might be a large mosaic of photographs in an irregular grid, where a small number are known to be "correct", with a requirement to adjust all the others to create a smooth final result. There could be millions of images, each with millions of pixels.
A possible approach is:
rem Seamless boundary by Poisson pasting. rem %1 is input background (without holes) rem %2 is input foreground, same size (relevant only when no guidance) rem %3 is input mask, same size rem mask is white where we want adjusted foreground, or black for background rem %4 is output. rem %5 0 or 1: whether to negate the mask. rem %6 optional guidance image rem %7 radius of final unsharp. 0=no unsharp. Default 0. @rem @rem Also uses: @rem ppTGT_SCORE target RMSE or PAE score. [default 0.001] @rem ppNUM_STEPS number of iteration steps between tests. [default 100] @rem ppPOST processing to apply to transition area at end, eg "unsharp 0x0.5+1+0". @rem @rem rfRLX_FUNC is a relaxation function. [default: average of 4 neighbours] @rem rfCOMP_METRIC default RMSE. PAE is more sensitive. @rem @if "%3"=="" findstr /B "rem @rem" %~f0 & exit /B 1 @setlocal enabledelayedexpansion @call echoOffSave call %PICTBAT%setInOut %1 pp set IN_A=%INFILE% set IN_B=%2 set MASK=%3 if not "%4"=="" if not "%4"=="." set OUTFILE=%4 set NEG_MASK=%5 if "%NEG_MASK%"=="." set NEG_MASK= if "%NEG_MASK%"=="" set NEG_MASK=0 if not %NEG_MASK%==0 if not %NEG_MASK%==1 exit /B 1 if %NEG_MASK%==0 ( set NEG1=negate set NEG2= ) else ( set NEG1= set NEG2=negate ) set GUID=%6 if "%GUID%"=="" set GUID=. set HAS_GUID=1 if "%GUID%"=="." set HAS_GUID=0 set UNSHP=%7 if "%UNSHP%"=="." set UNSHP= if "%UNSHP%"=="" set UNSHP=0 if "%ppPOST%"=="" ( set sUNSHP= ) else ( set sUNSHP=^^^( +clone %ppPOST% ^^^) %MASK% compose Over composite ) if "%ppTGT_SCORE%"=="" set ppTGT_SCORE=0.001 if "%ppNUM_STEPS%"=="" set ppNUM_STEPS=100 set TMPDIR=%TEMP%\ set TMP_APPRX=%TMPDIR%pp_tmp_apprx.miff set TMP1=%TMPDIR%pp_tmp1.miff set TMP2=%TMPDIR%pp_tmp2.miff :: Provide a first approximation: the background over the foreground. :: However, this seems to make performance worse. :: %IM%convert ^ :: %IN_B% ^ :: %IN_A% ^ :: compose Over composite ^ :: %TMP_APPRX% set TMP_APPRX=. if %HAS_GUID%==1 ( %IM%convert ^ %IN_A% ^ ^( %MASK% %NEG1% ^) ^ alpha off compose CopyOpacity composite ^ +depth ^ %TMP1% if ERRORLEVEL 1 exit /B 1 ) else ( %IM%convert ^ %IN_A% ^ %IN_B% ^ compose Mathematics ^ define "compose:args=0,0.5,0.5,0.5" composite ^ ^( %MASK% %NEG1% ^) ^ alpha off compose CopyOpacity composite ^ +depth ^ %TMP1% if ERRORLEVEL 1 exit /B 1 ) call %PICTBAT%relaxFillMS ^ %TMP1% %TMP_APPRX% %TMP2% ^ %ppTGT_SCORE% %ppNUM_STEPS% ^ . %GUID% if ERRORLEVEL 1 exit /B 1 if %HAS_GUID%==1 ( %IM%convert ^ %TMP2% ^ %sUNSHP% ^ +depth ^ %OUTFILE% if ERRORLEVEL 1 exit /B 1 ) else ( %IM%convert ^ %IN_B% ^ %TMP2% ^ compose Mathematics ^ define "compose:args=0,2,1,1" composite ^ +depth ^ ^( %MASK% %NEG2% ^) ^ alpha off ^ compose CopyOpacity composite ^ %IN_A% ^ +swap ^ compose Over composite ^ %sUNSHP% ^ +depth ^ %OUTFILE% if ERRORLEVEL 1 exit /B 1 ) call echoRestore @endlocal & set ppOUTFILE=%OUTFILE%& set rfmsITER=%rfmsITER%
rem Seamless boundary by Poisson pasting, with inner Dirichlet boundary. rem %1 is input background (without holes) rem %2 is input foreground, same size rem %3 is input mask, same size rem mask is white where we want adjusted foreground, or black for background rem %4 inner mask, white where we want exact foreground rem %5 is output. rem %6 0 or 1: whether to negate the mask. rem %7 optional guidance image @rem @rem Also uses: @rem ppTGT_SCORE target RMSE or PAE score. [default 0.001] @rem ppNUM_STEPS number of iteration steps between tests. [default 100] @rem @rem rfRLX_FUNC is a relaxation function. [default average of 4 neighbours] @rem rfCOMP_METRIC default RMSE. PAE is more sensitive. @rem @if "%4"=="" findstr /B "rem @rem" %~f0 & exit /B 1 @setlocal enabledelayedexpansion @call echoOffSave call %PICTBAT%setInOut %1 ppi set IN_A=%INFILE% set IN_B=%2 set MASK=%3 set MASK_IDB=%4 if "%MASK_IDB%"=="." set MASK_IDB= if not "%5"=="" if not "%5"=="." set OUTFILE=%5 set NEG_MASK=%6 if "%NEG_MASK%"=="." set NEG_MASK= if "%NEG_MASK%"=="" set NEG_MASK=0 set GUID=%7 if "%GUID%"=="" set GUID=. set HAS_GUID=1 if "%GUID%"=="." set HAS_GUID=0 if %NEG_MASK%==0 ( set NEG1=negate set NEG2= ) else ( set NEG1= set NEG2=negate ) if "%MASK_IDB%"=="" ( call %PICTBAT%poissonPaste ^ %IN_A% %IN_B% %MASK% %OUTFILE% %NEG_MASK% %GUID% goto finished ) if "%ppTGT_SCORE%"=="" set ppTGT_SCORE=0.001 if "%ppNUM_STEPS%"=="" set ppNUM_STEPS=100 set TMPDIR=%TEMP%\ set TMP1=%TMPDIR%ppi_tmp1.miff set TMP2=%TMPDIR%ppi_tmp2.miff set TMP_MASK=%TMPDIR%ppi_msk.png %IM%convert ^ %MASK% ^ ( %MASK_IDB% negate ) ^ compose Darken composite ^ %TMP_MASK% if %HAS_GUID%==1 ( %IM%convert ^ compose CopyOpacity ^ ^( %IN_A% ^( %MASK% %NEG1% ^) alpha off composite ^) ^ ^( %IN_B% ^( %MASK_IDB% %NEG2% ^) alpha off composite ^) ^ compose Over composite ^ %TMP1% if ERRORLEVEL 1 exit /B 1 ) else ( %IM%convert ^ %IN_A% ^ %IN_B% ^ compose Mathematics ^ define "compose:args=0,0.5,0.5,0.5" composite ^ ^( +clone fill gray^(50%%^) colorize 100 ^) ^ ^( %MASK_IDB% ^) ^ compose Over composite ^ +depth ^ ^( %TMP_MASK% %NEG1% ^) ^ alpha off compose CopyOpacity composite ^ %TMP1% if ERRORLEVEL 1 exit /B 1 ) call %PICTBAT%relaxFillMS ^ %TMP1% . %TMP2% ^ %ppTGT_SCORE% %ppNUM_STEPS% ^ . %GUID% if ERRORLEVEL 1 exit /B 1 if %HAS_GUID%==1 ( %IM%convert ^ %TMP2% ^ %OUTFILE% if ERRORLEVEL 1 exit /B 1 ) else ( %IM%convert ^ %IN_B% ^ %TMP2% ^ compose Mathematics ^ define "compose:args=0,2,1,1" composite ^ +depth ^ ^( %MASK% %NEG2% ^) ^ alpha off ^ compose CopyOpacity composite ^ %IN_A% ^ +swap ^ compose Over composite ^ +depth ^ %OUTFILE% if ERRORLEVEL 1 exit /B 1 ) :finished call echoRestore @endlocal & set ppiOUTFILE=%OUTFILE%
rem Given image %1, rem makes %2 rem from connected components that are at least %3 pixels. @rem %3 may have suffix 'c' or '%' for percentage or 'p' for proportion of image w*h. @rem Default 0. @rem @rem Each output connected component is the mean of its input pixels. @if "%1"=="" findstr /B "rem @rem" %~f0 & exit /B 1 @setlocal enabledelayedexpansion @call echoOffSave call %PICTBAT%setInOut %1 ccla if not "%2"=="" if not "%2"=="." set OUTFILE=%2 set THRESH=%3 if "%THRESH%"=="." set THRESH= if "%THRESH%"=="" set THRESH=0 set TH_LAST=%THRESH:~1% if "%TH_LAST%"=="^%" set TH_LAST=c if /I "%TH_LAST%"=="c" ( for /F "usebackq" %%L in (`%IM%identify ^ format "nTHRESH=%%[fx:w*h*%THRESH:~0,1%/100]" ^ %INFILE%`) do set %%L ) else if /I "%TH_LAST%"=="p" ( for /F "usebackq" %%L in (`%IM%identify ^ format "nTHRESH=%%[fx:w*h*%THRESH:~0,1%]" ^ %INFILE%`) do set %%L ) else ( set nTHRESH=%THRESH% ) if %nTHRESH%==0 ( set sTHRESH= ) else ( set "sTHRESH=define connectedcomponents:areathreshold^=%nTHRESH%" ) %IM%convert ^ %INFILE% ^ define connectedcomponents:verbose^=true ^ define connectedcomponents:meancolor=true ^ %sTHRESH% ^ connectedcomponents 4 ^ %OUTFILE% call echoRestore @endlocal & set cclaOUTFILE=%OUTFILE%
rem Given image %1, rem makes %2 rem from the largest %3 connected components. @rem @rem For performance, use the output from connCompLimitArea.bat @rem to reduce the number of components this script considers. @rem (or add area parameter to this script?) @rem @rem When an eliminated component is adjacent to more than one other component, @rem it may merge with the "wrong" one. @rem @rem Each output connected component is the mean of its input pixels. @if "%1"=="" findstr /B "rem @rem" %~f0 & exit /B 1 @setlocal enabledelayedexpansion @call echoOffSave call %PICTBAT%setInOut %1 ccln if not "%2"=="" if not "%2"=="." set OUTFILE=%2 set NUM=%3 if "%NUM%"=="." set NUM= if "%NUM%"=="" set NUM=0 %IM%convert ^ %INFILE% ^ define connectedcomponents:verbose^=true ^ connectedcomponents 8 ^ NULL: set sKEEP= set CNT=1 set LIM_AREA=0 for /F "usebackq skip=1 tokens=4" %%A in (`%IM%convert ^ %INFILE% ^ define connectedcomponents:verbose^=true ^ connectedcomponents 8 ^ NULL:`) do ( rem echo %%A if !CNT!==%NUM% set nTHRESH=%%A set /A CNT+=1 ) echo nTHRESH=%nTHRESH% %IM%convert ^ %INFILE% ^ define connectedcomponents:verbose=true ^ define connectedcomponents:meancolor=true ^ define connectedcomponents:areathreshold=%nTHRESH% ^ connectedcomponents 8 ^ %OUTFILE% set sKEEP= set CNT=1 set LIM_AREA=0 for /F "usebackq skip=1 tokens=1 delims=: " %%A in (`%IM%convert ^ %INFILE% ^ define connectedcomponents:verbose^=true ^ connectedcomponents 8 ^ NULL:`) do ( rem echo %%A if !CNT! LEQ %NUM% set sKEEP=!sKEEP!,%%A set /A CNT+=1 ) rem Remove initial comma set sKEEP=%sKEEP:~1% echo sKEEP=%sKEEP% :: FIXME: No, this makes the others transparent!! :: We need to find the limiting area. set UNIQ=ccln_uniq.png %IM%convert ^ %INFILE% ^ define connectedcomponents:verbose^=true ^ define connectedcomponents:keep=%sKEEP% ^ define connectedcomponents:meancolor=true ^ connectedcomponents 8 ^ uniquecolors ^ %UNIQ% %IM%identify %UNIQ% call echoRestore @endlocal & set cclnOUTFILE=%OUTFILE%
rem From image %1, rem make horizontal crosssection. @if "%1"=="" findstr /B "rem @rem" %~f0 & exit /B 1 @setlocal @call echoOffSave call %PICTBAT%setInOut %1 xs if not "%2"=="" if not "%2"=="." set OUTFILE=%2 set WW= for /F "usebackq" %%L in (`%IM%identify ^ format "WW=%%w\nHH=%%h\nW_2=%%[fx:int(w/2)]\nH_2=%%[fx:int(h/2)]" ^ %INFILE%`) do set %%L if "%WW%"=="" exit /B 1 set TMP=%TEMP%\xs.miff %IM%convert ^ %INFILE% ^ crop %WW%x1+0+%H_2% +repage ^ %TMP% call %PICTBAT%graphLineCol %TMP% . . . %OUTFILE% call echoRestore endlocal & set xsOUTFILE=%OUTFILE%
All images on this page were created by the commands shown, using:
%IM%identify version
Version: ImageMagick 6.9.53 Q16 x86 20160722 http://www.imagemagick.org Copyright: Copyright (C) 19992015 ImageMagick Studio LLC License: http://www.imagemagick.org/script/license.php Visual C++: 180040629 Features: Cipher DPC Modules OpenMP Delegates (builtin): bzlib cairo flif freetype jng jp2 jpeg lcms lqr openexr pangocairo png ps rsvg tiff webp xml zlib
To improve internet download speeds, some images may have been automatically converted (by ImageMagick, of course) from PNG to JPG.
Source file for this web page is seamlpm.h1. To recreate this web page, run "procH1 seamlpm".
This page, including the images except where shown otherwise, is my copyright. Anyone is permitted to use or adapt any of the code, scripts or images for any purpose, including commercial use.
Anyone is permitted to republish this page, but only for noncommercial use.
Anyone is permitted to link to this page, including for commercial use.
Page version v1.0 23October2014.
Page created 29Dec2016 14:27:25.
Copyright © 2016 Alan Gibson.