Python opencv 全景拼接 - 图1
© Karobben

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Main

I tried very hard to find a script which was able to stitch images. Other scripts were either too old to works on python3 or the functions are out of data. I final find a one in the post made by Adrian Rosebrock, 2018. Thanks Adrian Rosebrock, this script works very well and I’d like to note and share it here.

Origin Contributor: Adrian Rosebrock, 2018

Please reading the post from the original sites. It would be a great help.

pic_stitch.py

  1. #!/usr/bin/env python3
  2. '''
  3. https://www.pyimagesearch.com/2018/12/17/image-stitching-with-opencv-and-python/
  4. '''
  5. from imutils import paths
  6. import numpy as np
  7. import argparse
  8. import imutils
  9. import cv2
  10. # construct the argument parser and parse the arguments
  11. ap = argparse.ArgumentParser()
  12. ap.add_argument("-i", "--input", type=str, required=True,
  13. help="path to input directory of input to stitch")
  14. ap.add_argument("-o", "--output", type=str, required=True,
  15. help="path to the output image")
  16. ap.add_argument("-c", "--crop", type=int, default=0,
  17. help="whether to crop out largest rectangular region")
  18. ap.add_argument("-t", "--type", type=str, default="d",
  19. help="type of the input, 'd' is directory, 'v' is video")
  20. args = vars(ap.parse_args())
  21. # grab the paths to the input images and initialize our images list
  22. images = []
  23. if args["type"] == "d":
  24. print("[INFO] loading images...")
  25. imagePaths = sorted(list(paths.list_images(args["input"])))
  26. # loop over the image paths, load each one, and add them to our
  27. # images to stich list
  28. for imagePath in imagePaths:
  29. image = cv2.imread(imagePath)
  30. images.append(image)
  31. # initialize OpenCV's image sticher object and then perform the image
  32. # stitching
  33. print("[INFO] stitching images...")
  34. elif args["type"] =="v":
  35. cap=cv2.VideoCapture(args["input"])
  36. Num = 0
  37. while Num < cap.get(cv2.CAP_PROP_FRAME_COUNT):
  38. Num += 1
  39. if Num % 1 == 0:
  40. ret,frame=cap.read()
  41. images.append(frame)
  42. stitcher = cv2.createStitcher() if imutils.is_cv3() else cv2.Stitcher_create()
  43. (status, stitched) = stitcher.stitch(images)
  44. # if the status is '0', then OpenCV successfully performed image
  45. # stitching
  46. if status == 0:
  47. # check to see if we supposed to crop out the largest rectangular
  48. # region from the stitched image
  49. if args["crop"] > 0:
  50. # create a 10 pixel border surrounding the stitched image
  51. print("[INFO] cropping...")
  52. stitched = cv2.copyMakeBorder(stitched, 10, 10, 10, 10,
  53. cv2.BORDER_CONSTANT, (0, 0, 0))
  54. # convert the stitched image to grayscale and threshold it
  55. # such that all pixels greater than zero are set to 255
  56. # (foreground) while all others remain 0 (background)
  57. gray = cv2.cvtColor(stitched, cv2.COLOR_BGR2GRAY)
  58. thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
  59. # find all external contours in the threshold image then find
  60. # the *largest* contour which will be the contour/outline of
  61. # the stitched image
  62. cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
  63. cv2.CHAIN_APPROX_SIMPLE)
  64. cnts = imutils.grab_contours(cnts)
  65. c = max(cnts, key=cv2.contourArea)
  66. # allocate memory for the mask which will contain the
  67. # rectangular bounding box of the stitched image region
  68. mask = np.zeros(thresh.shape, dtype="uint8")
  69. (x, y, w, h) = cv2.boundingRect(c)
  70. cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1)
  71. # create two copies of the mask: one to serve as our actual
  72. # minimum rectangular region and another to serve as a counter
  73. # for how many pixels need to be removed to form the minimum
  74. # rectangular region
  75. minRect = mask.copy()
  76. sub = mask.copy()
  77. # keep looping until there are no non-zero pixels left in the
  78. # subtracted image
  79. while cv2.countNonZero(sub) > 0:
  80. # erode the minimum rectangular mask and then subtract
  81. # the thresholded image from the minimum rectangular mask
  82. # so we can count if there are any non-zero pixels left
  83. minRect = cv2.erode(minRect, None)
  84. sub = cv2.subtract(minRect, thresh)
  85. # find contours in the minimum rectangular mask and then
  86. # extract the bounding box (x, y)-coordinates
  87. cnts = cv2.findContours(minRect.copy(), cv2.RETR_EXTERNAL,
  88. cv2.CHAIN_APPROX_SIMPLE)
  89. cnts = imutils.grab_contours(cnts)
  90. c = max(cnts, key=cv2.contourArea)
  91. (x, y, w, h) = cv2.boundingRect(c)
  92. # use the bounding box coordinates to extract the our final
  93. # stitched image
  94. stitched = stitched[y:y + h, x:x + w]
  95. # write the output stitched image to disk
  96. cv2.imwrite(args["output"], stitched)
  97. # display the output stitched image to our screen
  98. cv2.imshow("Stitched", stitched)
  99. cv2.waitKey(0)
  100. # otherwise the stitching failed, likely due to not enough keypoints)
  101. # being detected
  102. else:
  103. print("[INFO] image stitching failed ({})".format(status))

How to use it

  1. tree test
  1. test
  2. ├── IMG_20210421_143828.jpg
  3. ├── IMG_20210421_143832.jpg
  4. └── IMG_20210421_143834.jpg
  1. python3 pic_stitch.py -i test -o result.png

Result:

Python opencv 全景拼接 - 图2

The Simplified Script

@MoonJian 2018

  1. import numpy as np
  2. import cv2
  3. from cv2 import Stitcher
  4. if __name__ == "__main__":
  5. img1 = cv2.imread('/home/ken/Desktop/test/IMG_20210421_143834.jpg')
  6. img2 = cv2.imread('/home/ken/Desktop/IMG_20210421_143832.jpg')
  7. #stitcher = cv2.createStitcher(False)
  8. stitcher = cv2.Stitcher.create(cv2.Stitcher_PANORAMA)# , 根据不同的OpenCV版本来调用
  9. (_result, pano) = stitcher.stitch((img1, img2))
  10. cv2.imshow('pano',pano)
  11. cv2.waitKey(0)

Stick A video

No work so well

  1. import numpy as np
  2. import cv2, sys, time
  3. from cv2 import Stitcher
  4. def progress_bar(i):
  5. print("\r", end="")
  6. print("Progress: {}%: ".format(i), "▋" * (int(i) // 2), end="")
  7. sys.stdout.flush()
  8. time.sleep(0.05)
  9. cap=cv2.VideoCapture("stitch.mp4")
  10. fps_c = cap.get(cv2.CAP_PROP_FRAME_COUNT)
  11. stitcher = cv2.Stitcher.create(cv2.Stitcher_PANORAMA)# , 根据不同的OpenCV版本来调用
  12. Num = 0
  13. ret,Result =cap.read()
  14. while Num <= fps_c:
  15. Num += 1
  16. ret,frame=cap.read()
  17. _result = 1
  18. if Num % 1 == 0:
  19. (_result, Result_tmp) = stitcher.stitch((Result, frame))
  20. progress_bar(100 * Num/fps_c )
  21. if _result == 0:
  22. Result = Result_tmp
  23. Ratio = [len(Result[0])/1080*2,len(Result)/1920*2]
  24. Ratio.sort()
  25. Ratio = Ratio[-1]
  26. test = cv2.resize(Result, (int(len(Result[0])/Ratio),int(len(Result)/Ratio)), interpolation = cv2.INTER_AREA)
  27. cv2.imshow("Stitched", test)
  28. if cv2.waitKey(1) & 0xFF == ord('q'):
  29. cv2.destroyAllWindows()
  30. break

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗