【问题标题】:How to crop image depends on Bounding boxes如何裁剪图像取决于边界框
【发布时间】:2019-09-16 23:05:36
【问题描述】:

我想根据边界框划分图像。图像由列名和行组成,但列没有任何边框,因此取决于它应该划分的间隙

我能够识别边界框,但我不明白应该裁剪哪些基础图像

large = cv2.imread("../forms/demo_1/crop/abc.jpg")
rgb = large

small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = cv2.morphologyEx(small, cv2.MORPH_GRADIENT, kernel)

_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

mask = np.zeros(bw.shape, dtype=np.uint8)

for idx in range(len(contours)):
    x, y, w, h = cv2.boundingRect(contours[idx])
    mask[y:y+h, x:x+w] = 0
    cv2.drawContours(mask, contours, idx, (255, 255, 255), -1)
    r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)

    if r > 0.4 and w > 3 and h > 8:
        cv2.rectangle(rgb, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2)
        print(x,y,x+w,y+h)

cv2.imshow('rects', rgb)
cv2.waitKey()
cv2.destroyAllWindows()

输入:

输出:

【问题讨论】:

    标签: python-3.x opencv image-processing


    【解决方案1】:

    这是您在 OpenCV 中从图像中裁剪矩形的方法(另请参阅 tutorial):

    import cv2
    large = cv2.imread("../forms/demo_1/crop/abc.jpg")
    
    # ... your code
    
    for idx in range(len(contours)):
    
        # ... your code to calculate x, y, w, g
    
        # example values. Use your calculated values here
        x, y, w, h = 0, 0, 60, 250
    
        crop = large[x:x+w, y:y+h]
    
        cv2.imshow('crop', crop)
        cv2.waitKey()
    

    【讨论】:

    • 是的,但这将是硬编码的。如果两个矩形之间的距离超过 150pts,我想裁剪图像。
    • 因此,您必须检查矩形之间的距离并仅根据此条件进行裁剪。像这样:for idx in range(len(contours)-1): if abs(xs[idx] - xs[idx+1]) > 150: crop = large[x:x+w, y:y+h]
    • xs 我的意思是你的contours 的所有计算 x 值的列表。 xs = [cv2.boundingRect(contours[idx])[0] for idx in range(len(contours))]
    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多