1. 程式人生 > 程式設計 >python+OpenCV實現影象拼接

python+OpenCV實現影象拼接

本文例項為大家分享了利用python和OpenCV實現影象拼接,供大家參考,具體內容如下

python+OpenCV實現image stitching

在最新的OpenCV官方文件中可以找到C++版本的Stitcher類的說明,但是python版本的還沒有及時更新,本篇對python版本的實現做一個簡單的介紹.

由於官方文件中還沒有python版本的Stitcher類的說明,因此只能自己去GitHub原始碼上找,以下是stitching的樣例:

from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
import sys

modes = (cv.Stitcher_PANORAMA,cv.Stitcher_SCANS)

parser = argparse.ArgumentParser(description='Stitching sample.')
parser.add_argument('--mode',type = int,choices = modes,default = cv.Stitcher_PANORAMA,help = 'Determines configuration of stitcher. The default is `PANORAMA` (%d),'
     'mode suitable for creating photo panoramas. Option `SCANS` (%d) is suitable '
     'for stitching materials under affine transformation,such as scans.' % modes)
parser.add_argument('--output',default = 'result.jpg',help = 'Resulting image. The default is `result.jpg`.')
parser.add_argument('img',nargs='+',help = 'input images')
args = parser.parse_args()

# read input images
imgs = []
for img_name in args.img:
  img = cv.imread(img_name)
  if img is None:
    print("can't read image " + img_name)
    sys.exit(-1)
  imgs.append(img)

stitcher = cv.Stitcher.create(args.mode)
status,pano = stitcher.stitch(imgs)

if status != cv.Stitcher_OK:
  print("Can't stitch images,error code = %d" % status)
  sys.exit(-1)

cv.imwrite(args.output,pano);
print("stitching completed successfully. %s saved!" % args.output)

上面寫了一大堆,然鵝,直接拿來用的話,用下面的程式碼可以了,簡單粗暴

import numpy as np
import cv2
from cv2 import Stitcher

if __name__ == "__main__":
  img1 = cv2.imread('1.jpg')
  img2 = cv2.imread('2.jpg')
  stitcher = cv2.createStitcher(False)
  #stitcher = cv2.Stitcher.create(cv2.Stitcher_PANORAMA),根據不同的OpenCV版本來呼叫
  (_result,pano) = stitcher.stitch((img1,img2))
  cv2.imshow('pano',pano)
  cv2.waitKey(0)

效果如下:

原圖:

python+OpenCV實現影象拼接

python+OpenCV實現影象拼接

拼接後的影象:

python+OpenCV實現影象拼接

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。