我找不到适合新图像零点轮廓的方法

I can't find a way to fit contour on new image zero point

我有一个二值图像,我想找到轮廓,将最大的一个轮廓放入新图像中,轮廓的大小就像一个矩形围绕着它一样。换句话说,将轮廓拟合到较小尺寸的新图像中。

查找轮廓例程正在为整个图像查找一个矩形,我不需要它。我看一个尺寸(宽度 - 1,高度 - 1)的轮廓并跳过它。

我想删除最大的矩形,然后将第二大的矩形放入新图像中。那个最大的矩形将成为新图像的界限。然后我想把轮廓画成一个新的白色图像。

我只是不太了解 OpenCV 以及执行此操作的最佳方法。

h = img.shape[0]
w = img.shape[1]
ret, img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
# are these the best find contours params?
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# paint a new image white
img = np.zeros((384, 640, 1), np.uint8)
img[:-1] = 255
# resize the contours
for i in range(0, len(contours)):
      for j in range(0, len(contours[i])):
         for k in range(0, len(contours[i][j])):
            if contours[i][j][k][1] != h - 1 or contours[i][j][k][0] != w -1:
               contours[i][j][k][1] = 384 * contours[i][j][k][1] / h
               contours[i][j][k][0] = 640 * contours[i][j][k][0] / w

我找不到找到整个文档的矩形的方法。最大的矩形是图像宽度 * 高度,但是在第二个中,只有黑色像素是可见的。

您在评论中声明您希望黑色像素作为图像的边界。在这种情况下,您可以使用下面的方法。它将图像加载为灰度,然后将其反转。所以原始图像中的白色现在是黑色(值:0),黑色变成白色(值:255)。接下来汇总所有行和列。总和大于零的第一个和最后一个 rows/columns 是原始图像中黑色像素的边界。您可以使用这些值来切片新图像。

结果:

代码:

    import cv2
    import numpy as np
    # load the image as grayscale
    img = cv2.imread('mQTiR.png',0)
    #invert the image
    img_inv = cv2.bitwise_not(img)
    # sum each row and each column of the inverted image
    sumOfCols = np.sum(img_inv, axis=0)
    sumOfRows = np.sum(img_inv, axis=1)
    # get the indexes of the rows/cols that are nonzero (=black in scan)
    nonzeroX = np.nonzero(sumOfCols)[0]
    nonzeroY = np.nonzero(sumOfRows)[0]
    # get the first and last indexes, these are the bounds of the roi
    minY = nonzeroY[0]
    maxY = nonzeroY[-1]
    minX = nonzeroX[0]
    maxX = nonzeroX[-1]
    #create subimage
    subimage = img[minY:maxY,minX:maxX]
    #display subimage
    cv2.imshow('Result',subimage)
    cv2.waitKey(0)
    cv2.destroyAllWindows()