def create_stitich(): in_path = os.path.join('..', 'data', 'interim', 'frames', '2019-08-13-1700') # 4Dec18 Ubir Geese out_path = os.path.join('..', 'data', 'interim', 'stitched') image_paths = sorted(list(paths.list_images(in_path))) print(image_paths) images = [] for image_path in image_paths: #if 'DJI_0455' in image_path or 'DJI_0456' in image_path: image = cv2.imread(image_path) images.append(image) stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) file_name = '{0}.jpg'.format(in_path.split(os.sep)[-1]) out_path = os.path.join(out_path, file_name) if status == 0: cv2.imwrite(out_path, stitched) cv2.imshow("Stitched", stitched) cv2.waitKey(0) else: print("[INFO] image stitching failed ({})".format(status))
def stitch_images(self, directory, output_path): # grab the paths to the input images and initialize our images list print("[INFO] loading images...") imagePaths = sorted(list(paths.list_images(directory))) images = [] # loop over the image paths, load each one, and add them to our # images to stich list for imagePath in imagePaths: image = cv2.imread(imagePath) images.append(image) # initialize OpenCV's image sticher object and then perform the image # stitching print("[INFO] stitching images...") stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) # if the status is '0', then OpenCV successfully performed image # stitching if status == 0: # write the output stitched image to disk cv2.imwrite(output_path, stitched) # display the output stitched image to our screen cv2.imshow("Stitched", stitched) cv2.waitKey(0) # otherwise the stitching failed, likely due to not enough keypoints) # being detected else: print("[INFO] image stitching failed ({})".format(status))
def stitch(images_path, output_path): print("[INFO] loading images...") imagePaths = sorted(list(paths.list_images(images_path))) images = [] # loop over the image paths, load each one, and add them to our # images to stitch list for imagePath in imagePaths: image = cv2.imread(imagePath) images.append(image) # initialize OpenCV's image stitcher object and then perform the image # stitching print("[INFO] stitching images...") stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) # if the status is '0', then OpenCV successfully performed image # stitching if status == 0: # write the output stitched image to disk cv2.imwrite(output_path, stitched) return True # otherwise the stitching failed, likely due to not enough keypoints) # being detected else: print("[INFO] image stitching failed ({})".format(status)) return False
def __stitchImages(self, firstImage, secondImage, matches, wtak, pSize, eThresh): # Create stitcher and stitch images stitcher = cv2.createStitcher(True) orb = cv2.ORB_create(WTA_K=wtak, scaleFactor=1.1, patchSize=pSize, edgeThreshold=eThresh) if (wtak == 4): bf = cv2.BFMatcher(cv2.NORM_HAMMING2, crossCheck=True) else: bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) try: status, image = stitcher.stitch([firstImage[2], secondImage[2]]) except: return (firstImage, secondImage) kp, desc = orb.detectAndCompute(image, None) #print(status) if (status == 0): # Draw first 10 matches. img3 = cv2.drawMatches(firstImage[2], firstImage[0], secondImage[2], secondImage[0], matches[:10], None, flags=2) return (kp, desc, image) else: return (firstImage, secondImage)
def stitch(images): stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() status, stitched = stitcher.stitch(images) # 四周填充黑色像素,再得到阈值图 stitched = cv2.copyMakeBorder(stitched, 10, 10, 10, 10, cv2.BORDER_CONSTANT, (0, 0, 0)) gray = cv2.cvtColor(stitched, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnt = max(cnts, key=cv2.contourArea) mask = np.zeros(thresh.shape, dtype="uint8") x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1) minRect = mask.copy() sub = mask.copy() # 开始while循环,直到sub中不再有前景像素 while cv2.countNonZero(sub) > 0: minRect = cv2.erode(minRect, None) sub = cv2.subtract(minRect, thresh) cnts, hierarchy = cv2.findContours(minRect.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnt = max(cnts, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(cnt) # 使用边界框坐标提取最终的全景图 return stitched[y:y + h, x:x + w]
def work(self): imagePaths = sorted(list(paths.list_images('images'))) ip = [] # 用于存放按次序的图片,因为拼接对次序敏感 tmp = imagePaths[0] for i in range(len(imagePaths)): ip.append(tmp[:12] + str(i) + tmp[13:]) images = [] for i, imagePath in enumerate(ip[:]): if i % 1 == 0: # 2为隔一张,不需要隔则设置为1即可 print(imagePath) image = cv2.imread(imagePath) image = cv2.rotate(image, 2) # 横向旋转,因为拼接对方向敏感 images.append(image) import time a = time.time() print('stitching images...') stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) print(time.time() - a) if status == 0: cv2.imwrite('res.png', stitched) return stitched else: print("got an error ({})".format(status))
def stitch(folder): time1 = time.time() VideoPrep.vid2imgs(folder) dir_path = os.path.dirname(folder) newpath = os.path.join(dir_path, "QuadOutputFrames") imgs = VideoPrep.findFrames(newpath) # intimgs = VideoPrep.chooseFrame(newpath) # imgs=[] # print(str(len(intimgs))) # for i in range (0, len(intimgs)): # paus = intimgs[i] # img = np.array(paus) # imgs.append(img) # for i in range(0, len(imgs)): # print("count: " + str(i)) # plt.imshow(imgs[i]) # plt.show() stitcher = cv2.createStitcher(False) result = np.empty(shape=[2048, 2048]) ret, result = stitcher.stitch(imgs, result) # cv2.imwrite("/Users/amolsingh/Documents/OhgamiLab/Videos/QuadOutputFrames/QuadStitched.jpg", result) cv2.imwrite(os.path.join(newpath, "QuadStitched.jpg"), result) time2 = time.time() fintime = time2 - time1 print("Time: " + str(fintime))
def stackNstitch1vid(folder): time1 = time.time() VideoPrep.vid2imgs1vid(folder) for n in range(1, 486): stacked = StackingMain.stacker( "/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/OutputFrames%d" % n) cv2.imwrite( "/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/final/frame%d.jpg" % n, stacked) path, dirs, files = os.walk( "/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/final" ).__next__() # path, dirs, files = os.walk("/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/OutputFrames(singlebatch)").__next__() size = len(files) inp = [] for i in range(1, size): a = cv2.imread( "/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/final/frame%d.jpg" % i) # a = cv2.imread("/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/OutputFrames(singlebatch)/frame%d.jpg" %i) inp.append(a) result = np.empty(shape=[4000, 4000]) stitcher = cv2.createStitcher(False) ret, result = stitcher.stitch(inp, result) cv2.imwrite( "/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/final/stitched.jpg", result) # cv2.imwrite("/Users/amolsingh/Documents/OhgamiLab/Videos/FramesStackNStitch/final/stitched(singlebatch).jpg", result) time2 = time.time() fintime = time2 - time1 print("Time: " + str(fintime))
def stich_images(img_dir="./shelf"): """ stitch images in a given directory """ print("[INFO] loading images...") imagePaths = sorted(list(paths.list_images(img_dir))) images = [] # loop over the image paths, load each one, and add them to our # images to stitch list for imagePath in imagePaths: image = cv2.imread(imagePath) images.append(image) print("[INFO] stitching images...") stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) # if the status is 0, then OpenCV successfully performed image stitching if status == 0: # write the output stitched image to disk cv2.imwrite("./pano.jpg", stitched) # display the output stitched image to our screen # cv2.imshow("Stitched", stitched) # cv2.waitKey(0) # otherwise the stitching failed, likely due to not enough keypoints) being detected else: print("[INFO] image stitching failed ({})".format(status))
def create_modified_stitcher(): stitcher = cv2.createStitcher(False) #don't use GPU stitcher.setPanoConfidenceThresh(.05) # changed from .5, basically makes it a 'make a panorama at any cost, even if it's terrible' function stitcher.setRegistrationResol(.6) # changed from .5, expands the image a little bit, might change later stitcher.setCompositingResol(-1) # doesnt really make a difference, left at default stitcher.setSeamEstimationResol(.1) # this is supposed to smooth out seam connections, but doesn't seem to really matter. also heavily increases computation time return stitcher
def stitch(imgs): stitcher = cv2.createStitcher() ret, pano = stitcher.stitch(imgs) if ret == cv2.STITCHER_OK: return pano else: print('Error during stiching %d' % ret)
def image_stitch(imgs): stitcher = cv2.createStitcher(False) result = stitcher.stitch(imgs) if result[0] != 0: print("Image stitching is failed, please check the input images!") return None return result[1]
def stitch(image_path, output_path, output_path1, crop): print("[INFO] loading images...") imagePaths = sorted(list(paths.list_images(image_path))) images = [] # loop over the image paths, load each one, and add them to our # images to stitch list for imagePath in imagePaths: image = cv2.imread(imagePath) images.append(image) # initialize OpenCV's image sticher object and then perform the image # stitching print("[INFO] stitching images...") stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) if status == 0: if crop: print("cropping") cropped = crop(stitched) cv2.imwrite(output_path, stitched) cv2.imwrite(output_path1, cropped) else: cv2.imwrite(output_path, stitched) print('done') else: print('not enough features')
def upload_file(): if request.method == 'POST': # check if the post request has the files part if 'files[]' not in request.files: flash('No file part') return redirect(request.url) files = request.files.getlist('files[]') for file in files: if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) flash('File(s) successfully uploaded') print("[INFO] loading images...") images = [] for imagePath in files: print(type(imagePath)) print(imagePath) for imagePath in files: image = cv2.imread(imagePath) cv2.imshow("Image", image) # image=cv2.resize(image, (64,64)) images.append(image) print("[INFO] stitching images...") stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) if status == 0: # cv2.imwrite(args["output"], stitched) cv2.imshow("Stitched", stitched) cv2.waitKey(0) else: print("[INFO] image stitching failed ({})".format(status)) return redirect('/')
def stitch(images): stitcher = cv2.createStitcher() (status, stitched) = stitcher.stitch(images) if status == 0: return stitched else: raise Exception(f"Status: {status}")
def hu(img1, img2, i): stitcher = cv2.createStitcher(False) foo = cv2.imread(img1) bar = cv2.imread(img2) result = stitcher.stitch((foo, bar)) cv2.imwrite("../scene/res2/{}.jpg".format(i), result[1])
def main(): # 加载参数 args = parser_args() print(args.images) # 获取图像列表 imagePaths = sorted(list(paths.list_images(args.images))) images = [] # 加载图像 for imagePath in imagePaths: image = cv2.imread(imagePath) images.append(image) # 拼接 print("[INFO] stitching images...") stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, stitched) = stitcher.stitch(images) if status == 0: # status=0时,表示拼接成功 if args.crop > 0: # 边界填充 stitched = cv2.copyMakeBorder(stitched, 10, 10, 10, 10, cv2.BORDER_CONSTANT, (0, 0, 0)) # 转为灰度图进行并二值化 gray = cv2.cvtColor(stitched, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1] # 获取轮廓 cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) mask = np.zeros(thresh.shape, dtype="uint8") (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1) minRect = mask.copy() sub = mask.copy() while cv2.countNonZero(sub) > 0: minRect = cv2.erode(minRect, None) sub = cv2.subtract(minRect, thresh) cnts = cv2.findContours(minRect.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) (x, y, w, h) = cv2.boundingRect(c) # 取出图像区域 stitched = stitched[y:y + h, x:x + w] cv2.imwrite(args.output, stitched) else: print("[INFO] image stitching failed ({})".format(status))
def make_mosainic(input_files, output_file): if sys.platform == 'win32': result = (0, cv2.imread('cache/r.jpg')) else: stitcher = cv2.createStitcher(False) result = stitcher.stitch(tuple(cv2.imread(fn) for fn in input_files)) cv2.imwrite(output_file, result[1]) return result[1].shape[:2]
def make_panorama(imgs_list, pathout, frames): stitcher = cv2.createStitcher(False) blurry_detect(imgs_list) # 첫번째 초기 이미지 pop temp_img = imgs_list.pop(0) # result 초기화 result = stitcher.stitch([temp_img, temp_img]) # count 초기화 cnt = 1 final = result # 모든 img 한번씩 stitch for img in imgs_list: # count 출력 및 증가 print(cnt) cnt = cnt + 1 # result[0] 코드 번호 # result[1] img value # result value 값이 있으면 result value 값과 현재 img stitch # result value 값이 없으면 초기 이미지와 현재 img stitch if (np.any(result[1] != None)): result = stitcher.stitch([img, result[1]]) else: result = stitcher.stitch([temp_img, img]) # 에러 코드 출력 if (result[0] != 0): print("error for code", result[0]) else: result = draw_line(result[1]) final = result print("done") cv2.imshow(str(frames) + " Frames Result", final[1]) '''error code OK = 0, ERR_NEED_MORE_IMGS = 1, ERR_HOMOGRAPHY_EST_FAIL = 2, ERR_CAMERA_PARAMS_ADJUST_FAIL = 3 ''' now = time.localtime() file_name = pathout + "\\" + str( frames) + "FPS_%04d-%02d-%02d_%02d-%02d-%02d.jpg" % ( now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) cv2.imwrite(file_name, final[1]) # save frame as JPEG file cv2.waitKey(0) cv2.destroyAllWindows()
def opencvStitching(list_img): '''create panorama using cv2.createStitcher()''' #create panorama using cv2.createStitcher() stitcher = cv2.createStitcher() (status, stitched) = stitcher.stitch(list_img) # create a 10 pixel border surrounding the stitched image stitched = cv2.copyMakeBorder(stitched, 10, 10, 10, 10, cv2.BORDER_CONSTANT, (0, 0, 0)) # convert the stitched image to grayscale and threshold it # such that all pixels greater than zero are set to 255 # (foreground) while all others remain 0 (background) gray = cv2.cvtColor(stitched, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1] # find all external contours in the threshold image then find # the *largest* contour which will be the contour/outline of # the stitched image cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) # allocate memory for the mask which will contain the # rectangular bounding box of the stitched image region mask = np.zeros(thresh.shape, dtype="uint8") (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1) # create two copies of the mask: one to serve as our actual # minimum rectangular region and another to serve as a counter # for how many pixels need to be removed to form the minimum # rectangular region minRect = mask.copy() sub = mask.copy() # keep looping until there are no non-zero pixels left in the # subtracted image while cv2.countNonZero(sub) > 0: # erode the minimum rectangular mask and then subtract # the thresholded image from the minimum rectangular mask # so we can count if there are any non-zero pixels left minRect = cv2.erode(minRect, None) sub = cv2.subtract(minRect, thresh) # find contours in the minimum rectangular mask and then # extract the bounding box (x, y)-coordinates cnts = cv2.findContours(minRect.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) (x, y, w, h) = cv2.boundingRect(c) # use the bounding box coordinates to extract the our final # stitched image stitched = stitched[y:y + h, x:x + w] return stitched
def multi_stitch(img_array): stitcher = cv2.createStitcher(False) ims = [] for i, img in enumerate(img_array): ims.append(cv2.imread(img)) output = stitcher.stitch(tuple(ims)) return output
def stitch(img_pair): stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() imgs = [img_pair[0], img_pair[1]] (status, stitched) = stitcher.stitch(imgs) if status == 0: return stitched else: return None
def stitch_images(self): if self.flags["image_loaded"]: # call the cv2 stitcher class and use stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() (status, self.stitched) = stitcher.stitch(self.images) if status == 0: self.flags["image_stitched"] = True
def stitch_images(self): stitcher = cv2.createStitcher(False) filtered_buffer = filter(None, self.image_buffer) output = stitcher.stitch( map(lambda ext_img: ext_img.cv_img(), filtered_buffer)) panorama = output[1] if panorama != None: # Successfully stitched buffer self.publish_image(panorama)
def stitch(left, right, output_folder, use_opencv): create_folder(output_folder) descriptor = cv2.xfeatures2d.SIFT_create() print(left.shape) print(right.shape) if not use_opencv: ratio = 0.75 min_match = 10 print('tests') gray_left = cv2.cvtColor(left, cv2.COLOR_BGR2GRAY) gray_right = cv2.cvtColor(right, cv2.COLOR_BGR2GRAY) (kps_left, features_left) = descriptor.detectAndCompute(gray_left, None) (kps_right, features_right) = descriptor.detectAndCompute(gray_right, None) # bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True) # matches = bf.match(features_left,features_right) matcher = cv2.BFMatcher() raw_matches = matcher.knnMatch(features_left, features_right, k=2) good_points = [] good_matches = [] for m1, m2 in raw_matches: if m1.distance < ratio * m2.distance: good_points.append((m1.trainIdx, m1.queryIdx)) good_matches.append([m1]) if len(good_points) > min_match: image1_kp = np.float32([kps_left[i].pt for (_, i) in good_points]) image2_kp = np.float32([kps_right[i].pt for (i, _) in good_points]) H, status = cv2.findHomography(image2_kp, image1_kp, cv2.RANSAC, 5.0) result = cv2.warpPerspective( right, H, (right.shape[1] + left.shape[1], right.shape[0])) result[0:left.shape[0], 0:left.shape[1]] = left cv2.imwrite(os.path.join(output_folder, 'uncropped.png'), result) # plt.imshow(result) cropped = crop(result) cv2.imwrite(os.path.join(output_folder, 'cropped.png'), cropped) # plt.imshow(cropped) else: stitcher = cv2.createStitcher() (status, stitched) = stitcher.stitch([left, right]) if status == 0: cv2.imwrite( os.path.join(output_folder, 'opencv_stitcher_uncropped.png'), stitched) cropped = crop(stitched) cv2.imwrite( os.path.join(output_folder, 'opencv_stitcher_cropped.png'), cropped)
def test_simple(self): img1 = self.get_sample('stitching/a1.png') img2 = self.get_sample('stitching/a2.png') stitcher = cv.createStitcher(False) stitcher.estimateTransform((img1, img2)) result, _ = stitcher.composePanorama((img1, img2)) assert result == 0
def mode_changed(self, text): new_mode = self.modes[text] print("prev mode {}".format(self.mode)) if new_mode != self.mode: # Need to recreate stitcher object. self.mode = new_mode print("Recreated new stitcher {}".format(self.mode)) self.stitcher = cv2.createStitcher(self.mode) # self.stitch()
def perform_stitching(self, output_file): stitcher = cv2.createStitcher() if imutils.is_cv3( ) else cv2.Stitcher_create() stitched = np.zeros( (self.imgs[0].shape[0], self.imgs[0].shape[1] * len(self.imgs))) (status, stitched) = stitcher.stitch(self.imgs, stitched) if status == 0: # write the output stitched image to disk cv2.imwrite(output_file, stitched) return status, stitched
def stitch(files): # 拼接成全景图 imgs = [] for file in files: imgs.append(cv2.imread(DIR + '/' + file)) try_use_gpu = False stitcher = cv2.createStitcher(try_use_gpu) status, pano = stitcher.stitch(imgs) if status == 0: return pano else: return None
def stitch_images(self): print("Stitching images, please wait....") self.stitcher = ocv.createStitcher(try_use_gpu=False) (self.status, self.stitched) = self.stitcher.stitch(self.images) self.images = [] if self.status == 0: print("Image stitching completed") ocv.imshow("stitched image", self.stitched) ocv.waitKey(0) ocv.destroyAllWindows() else: print("Cannot stitch images. " + " Error code " + str(self.status))
def test_simple(self): img1 = self.get_sample('stitching/a1.png') img2 = self.get_sample('stitching/a2.png') stitcher = cv2.createStitcher(False) (_result, pano) = stitcher.stitch((img1, img2)) #cv2.imshow("pano", pano) #cv2.waitKey() self.assertAlmostEqual(pano.shape[0], 685, delta=100, msg="rows: %r" % list(pano.shape)) self.assertAlmostEqual(pano.shape[1], 1025, delta=100, msg="cols: %r" % list(pano.shape))