如何裁剪图像取决于边界框

时间:2019-09-16 09:33:34

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

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

我能够识别边界框,我不了解应裁剪哪些基础图像

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()

输入: Input Image

输出: Output_1 Output_2

1 个答案:

答案 0 :(得分:0)

这是在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()