Hello, I would like to create a panorama using a folder. It works good until 6 images but the memory increases fast and stops the processus.
Here is my code :
import numpy as np
import cv2 as cv
import sys
import os
def initialize():
if len(sys.argv) != 2:
print("Usage: python3 SIFT.py <directory>")
sys.exit(1)
directory = sys.argv[1]
files = []
for filename in os.listdir(directory):
f = os.path.join(directory,filename)
files.append(f)
files.sort()
return files
def completeImages(img1,img2):
if(img1.shape!=img2.shape):
maxHeight = img1.shape[0] if img1.shape[0] >= img2.shape[0] else img2.shape[0]
maxWidth = img1.shape[1] if img1.shape[1] >= img2.shape[1] else img2.shape[1]
img1 = cv.copyMakeBorder(img1, 0, maxHeight - img1.shape[0], 0, maxWidth - img1.shape[1], cv.BORDER_CONSTANT, value=[0,0,0])
img2 = cv.copyMakeBorder(img2, 0, maxHeight - img2.shape[0], 0, maxWidth - img2.shape[1], cv.BORDER_CONSTANT, value=[0,0,0])
return img1,img2
def warpImages(img1,img2,H):
rows1, cols1 = img1.shape[:2]
rows2, cols2 = img2.shape[:2]
list_of_points_1 = np.float32([[0,0], [0,rows1], [cols1,rows1], [cols1,0]]).reshape(-1,1,2)
temp_points = np.float32([[0,0], [0,rows2], [cols2,rows2], [cols2,0]]).reshape(-1,1,2)
list_of_points_2 = cv.perspectiveTransform(temp_points, H)
list_of_points = np.concatenate((list_of_points_1, list_of_points_2), axis=0)
[x_min, y_min] = np.int32(list_of_points.min(axis=0).ravel() - 0.5)
[x_max, y_max] = np.int32(list_of_points.max(axis=0).ravel() + 0.5)
translation_dist = [-x_min, -y_min]
H_translation = np.array([[1, 0, translation_dist[0]], [0, 1, translation_dist[1]], [0,0,1]])
output_img = cv.warpPerspective(img1, H_translation.dot(H), (x_max-x_min, y_max-y_min))
output_img[translation_dist[1]:rows1+translation_dist[1], translation_dist[0]:cols1+translation_dist[0]] = img2
return output_img
def stitch2images(img1,img2):
img_1, img_2 = completeImages(img1,img2)
kp_1, desc_1 = sift.detectAndCompute(img_1,None)
kp_2, desc_2 = sift.detectAndCompute(img_2,None)
matches = bf.knnMatch(desc_1, desc_2, k=2)
good_matches = []
for m,n in matches:
if m.distance < 0.75*n.distance:
good_matches.append(m)
src_pts = np.float32([ kp_1[m.queryIdx].pt for m in good_matches ]).reshape(-1,1,2)
dst_pts = np.float32([ kp_2[m.trainIdx].pt for m in good_matches ]).reshape(-1,1,2)
H, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)
warp_img = warpImages(img_1,img_2,H)
return warp_img
files = initialize()
sift = cv.SIFT_create()
bf = cv.BFMatcher()
res = cv.imread(files[0])
for i in range(1,len(files)-3):
currentImg = cv.imread(files[i])
res = stitch2images(res,currentImg)
res = cv.resize(res,(2000,1000))
cv.imshow("Final",res)
cv.waitKey(0)