m0_64018569 2023-07-13 03:09 采纳率: 78.6%
浏览 44
已结题

图像配准,代码哪里出错了

from imutils import paths
import numpy as np
import imutils
import cv2

images = 'C:\learn\python\images\scottsdale'  # 输入图片文件夹路径
output = 'C:\learn\python\output.png'  # 输出图片名称
crop = True
imagePaths = sorted(list(paths.list_images(images)))
images = []

# 读取文件夹图片
for imagePath in imagePaths:
    image = cv2.imread(imagePath)
    images.append(image)

# 创建缝合器
stitcher = cv2.Stitcher_create()
(status, stitched) = stitcher.stitch(images)

# status:状态,0代表成功
if status == 0:
    # 裁剪图像
    if crop:
        # 在拼图周围添加2像素
        stitched = cv2.copyMakeBorder(stitched, 2, 2, 2, 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作为不断腐蚀的矩形
        # sub作为阈值图像和minRect的插值来进行判断
        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(output, stitched)

else:
    print("拼接失败,错误码:{}".format(status))

img

  • 写回答

3条回答 默认 最新

  • 关注

    cv2.copyMakeBorder()函数的调用存在问题,第26行改成

    stitched = cv2.copyMakeBorder(stitched, 2, 2, 2, cv2.BORDER_CONSTANT, value=(0, 0, 0))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 7月21日
  • 已采纳回答 7月13日
  • 创建了问题 7月13日