OpenCV  4.8.0
Open Source Computer Vision
samples/python/stitching.py

A basic example on image stitching in Python.

1 #!/usr/bin/env python
2 
3 '''
4 Stitching sample
5 ================
6 
7 Show how to use Stitcher API from python in a simple way to stitch panoramas
8 or scans.
9 '''
10 
11 # Python 2/3 compatibility
12 from __future__ import print_function
13 
14 import numpy as np
15 import cv2 as cv
16 
17 import argparse
18 import sys
19 
20 modes = (cv.Stitcher_PANORAMA, cv.Stitcher_SCANS)
21 
22 parser = argparse.ArgumentParser(prog='stitching.py', description='Stitching sample.')
23 parser.add_argument('--mode',
24  type = int, choices = modes, default = cv.Stitcher_PANORAMA,
25  help = 'Determines configuration of stitcher. The default is `PANORAMA` (%d), '
26  'mode suitable for creating photo panoramas. Option `SCANS` (%d) is suitable '
27  'for stitching materials under affine transformation, such as scans.' % modes)
28 parser.add_argument('--output', default = 'result.jpg',
29  help = 'Resulting image. The default is `result.jpg`.')
30 parser.add_argument('img', nargs='+', help = 'input images')
31 
32 __doc__ += '\n' + parser.format_help()
33 
34 def main():
35  args = parser.parse_args()
36 
37  # read input images
38  imgs = []
39  for img_name in args.img:
40  img = cv.imread(cv.samples.findFile(img_name))
41  if img is None:
42  print("can't read image " + img_name)
43  sys.exit(-1)
44  imgs.append(img)
45 
46  stitcher = cv.Stitcher.create(args.mode)
47  status, pano = stitcher.stitch(imgs)
48 
49  if status != cv.Stitcher_OK:
50  print("Can't stitch images, error code = %d" % status)
51  sys.exit(-1)
52 
53  cv.imwrite(args.output, pano)
54  print("stitching completed successfully. %s saved!" % args.output)
55 
56  print('Done')
57 
58 
59 if __name__ == '__main__':
60  print(__doc__)
61  main()