【问题标题】:How can I apply the contours of a downsized image to the original image?如何将缩小图像的轮廓应用于原始图像?
【发布时间】:2021-01-04 15:35:41
【问题描述】:

我有一个完美的代码可以用 OpenCV 找到轮廓。但是,我的代码处理缩小的图像以提高计算速度。如何将缩小图像的轮廓应用于原始图像?

这是我的 Python 代码:

# Image Read and Resizing
source_image = cv.imread(image_path)
copied_image = source_image.copy()
copied_image = imutils.resize(copied_image, height=500)

# Apply GaussianBlur + OTSU-Thresholding
grayscale_image = cv.cvtColor(copied_image, cv.COLOR_BGR2GRAY)
grayscale_image = cv.GaussianBlur(grayscale_image, (5, 5), 0)
ret, grayscale_image = cv.threshold(grayscale_image, 200, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)

# Find Contours
contours, hierarchy = cv.findContours(grayscale_image, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
contour_sizes = [(cv.contourArea(contour), contour) for contour in contours]
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]

# Crop Image
x, y, w, h = cv.boundingRect(biggest_contour)
cropped_image = copied_image[y:y + h, x:x + w]

copied_image 小于source_image。我只使用了最大的轮廓。现在,我想用source_image 应用找到的轮廓。但是,在我的代码中,获取的轮廓是基于copied_image

【问题讨论】:

    标签: python opencv contour


    【解决方案1】:

    如果您可以接受 1 或 2 个像素的(不)精度,那么一个非常简单的解决方案就是将边界矩形的 x, y, w, h 值乘以相应的缩放因子:

    import cv2
    import numpy as np
    
    # Set up some test image
    image = np.zeros((400, 400), np.uint8)
    image = cv2.circle(image, (160, 160), 80, 255, cv2.FILLED)
    
    # Find contour, and determine original bounding rectangle
    cnt_orig = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
    x, y, w, h = cv2.boundingRect(cnt_orig[0])
    print('Original bounding rectangle: ', x, y, w, h)
    
    # Downsize image
    image_small = cv2.resize(image.copy(), (124, 287))
    
    # Determine scaling factors
    scale_x = image.shape[1] / image_small.shape[1]
    scale_y = image.shape[0] / image_small.shape[0]
    
    # Find contour, and determine reconstructed bounding rectangle w.r.t. the scaling factors
    cnt_small = cv2.findContours(image_small, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
    x, y, w, h = cv2.boundingRect(cnt_small[0]) * np.array([scale_x, scale_y, scale_x, scale_y])
    print('Reconstructed bounding rectangle: ', x, y, w, h)
    

    输出:

    Original bounding rectangle:  80 80 161 161
    Reconstructed bounding rectangle:  80.64... 79.44... 161.29... 161.67...
    

    注意:使用的测试图像非常简单。在更复杂的图像中找到更复杂的轮廓时,(不)准确度可能会提高。

    ----------------------------------------
    System information
    ----------------------------------------
    Platform:    Windows-10-10.0.16299-SP0
    Python:      3.8.5
    NumPy:       1.19.4
    OpenCV:      4.4.0
    ----------------------------------------
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2017-06-10
      • 2021-12-23
      • 2012-11-17
      • 2021-06-12
      • 2021-01-05
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      相关资源
      最近更新 更多