# How to stitch two images together

I have talk about how to catenate two images whose have same part totally in my this post.

But in this case two images have similar information, not totally same.

img1 = Import @ "https://i.sstatic.net/oc1L8.jpg"


img2 = Import @ "https://i.sstatic.net/GGTBv.jpg"


This is my expected result

If I use ImageAlign, I just can see the second image. How to catenate the first image?

img3 = ImageAlign[img1, img2];
ImageCompose[img3, {img1, .5}]


I can use ImageCorrespondingPoints to see the corresponding points

matches = ImageCorrespondingPoints[##] & @@ images;
Show[#1, Graphics[{Red, MapIndexed[Inset[#2[[1]], #1] & , #2]}],
ImageSize -> 400] &, {images, matches}];
dim = ImageDimensions[First[images]];
pos = {First[matches], {First[dim], 0} + # & /@
RescalingTransform[
Transpose[{{0, 0}, ImageDimensions[Last[images]]}],
Transpose[{{0, 0}, ImageDimensions[First[images]]}]][
Last[matches]]};
Show[ImageAssemble[{First[images], ImageResize[Last[images], dim]}],
Epilog -> {Thick,
Unevaluated[RandomColor[]], {1, -1, 2}]}, ImageSize -> 500]


But I don't know how to connect them.

• This VERY well-studied problem is called "image stitching" or "image compositing." en.wikipedia.org/wiki/Image_stitching Commented Sep 6, 2017 at 0:34
• Possible duplicate of Can Mathematica recompose an image? Commented Sep 6, 2017 at 8:02
• @mattiav27 NoNoNo,please cancel the duplicate tag,because those image have same part in that post,but in my this post,this two images just have similar part.
– yode
Commented Sep 6, 2017 at 9:02
• @Kuba Need your privilege here,if you agree with my comment upstair
– yode
Commented Sep 6, 2017 at 12:34
• @yode in order to do what?
– Kuba
Commented Sep 6, 2017 at 17:00

Is this what you need?

padded = ImagePad[img1, {{#, #}, {#2, #2}} & @@ ImageDimensions@img2];



Padding may be expensive for ImageAlign so if you know where it should fit you can pad from one or two sides not around.

• Fun..it is a magic.I cannot imagine it can be solve by such simple method..
– yode
Commented Sep 5, 2017 at 12:21
• And there I was messing about with ImageCorrespondingPoints. Commented Sep 5, 2017 at 12:21
• @aardvark2012 Don't blame yourself, I don't understand why this is not more straightforward. I mean, this is an obvious thing to want for two images, why would anyone want to crop the second one?
– Kuba
Commented Sep 5, 2017 at 12:23

Can supplement Kuba's nice answer with a geometric transform from the documentation.

 {w, h} = ImageDimensions[img2];
{e, tr} = FindGeometricTransform[img1, img2];
tmp = ImagePerspectiveTransformation[img2, tr, DataRange -> Full,
PlotRange -> {{0, First@tr[{w, 0}]}, {0, h}}];
ImageCompose[tmp, {img1, 1}, Round@({w, h}/2)]


yielding:

• Neat and faster :) +1
– Kuba
Commented Sep 6, 2017 at 8:22