Skip to content

Instantly share code, notes, and snippets.

@douglasrizzo
Last active September 18, 2019 18:01
Show Gist options
  • Save douglasrizzo/978f083f613710c47362790e1fd2a981 to your computer and use it in GitHub Desktop.
Save douglasrizzo/978f083f613710c47362790e1fd2a981 to your computer and use it in GitHub Desktop.
Stitch multiple images into one using OpenCV
##############################################################################
# Copyright 2019 Douglas De Rizzo Meneghetti
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
##############################################################################
# Usage
# python stitch.py [DIRECTORY]
#
# Will read all JPG files in DIRECTORY and stitch them into
# one stitched.jpg file. Default directory is .
import cv2
import os
import sys
filepath = '.' if len(sys.argv) == 1 else sys.argv[1]
print('Loading images from {}'.format(filepath))
files = [os.path.join(filepath, i) for i in os.listdir(filepath) if i.endswith('.jpg')]
print(' Found {} jpg files'.format(len(files)))
print('Loading images...')
ims = [cv2.imread(x) for x in files]
s = cv2.Stitcher_create()
print('Stitching...')
(status, stitched) = s.stitch(ims)
if status != 0:
raise ValueError('Error {}'.format(status))
else:
outfile = os.path.join(filepath, 'stitched.jpg')
cv2.imwrite(outfile, stitched)
print('Done. Output saved to {}'.format(outfile))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment