This question already has answers here:
How to remove whitespace from an image in OpenCV?

(2个答案)


在10个月前关闭。




我有以下图像是收据图像,并且收据周围有很多空白。我想裁剪空白。我无法手动裁剪,因此我正在寻找一种可以做到的方式。

python - 如何在opencv中从图像中删除多余的空格?-LMLPHP

裁剪一:

python - 如何在opencv中从图像中删除多余的空格?-LMLPHP

在以下帖子中尝试了此代码:How to remove whitespace from an image in OpenCV?
gray = load_image(IMG_FILE) # image file
gray = 255*(gray < 128).astype(np.uint8)
coords = cv2.findNonZero(gray) # Find all non-zero points (text)
x, y, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
rect = load_image(IMG_FILE)[y:y+h, x:x+w] # Crop the image - note we do this on the original image

它裁剪了空白的一小部分。

最佳答案

这是一个简单的方法:

  • 获取二进制图像。 加载图像,转换为灰度,应用大的高斯模糊,然后使用Otsu的阈值
  • 执行形态运算。 我们首先使用小核进行变形打开以消除噪声,然后使用大核进行变形关闭以组合轮廓
  • 查找封闭的边界框并裁剪ROI。 我们找到所有非零点的坐标,找到边界矩形,并裁剪ROI。


  • 这是检测到的以绿色突出显示的ROI的ROI

    python - 如何在opencv中从图像中删除多余的空格?-LMLPHP

    投资返回率下降
    import cv2
    
    # Load image, grayscale, Gaussian blur, Otsu's threshold
    image = cv2.imread('1.jpg')
    original = image.copy()
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (25,25), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    
    # Perform morph operations, first open to remove noise, then close to combine
    noise_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, noise_kernel, iterations=2)
    close_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))
    close = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, close_kernel, iterations=3)
    
    # Find enclosing boundingbox and crop ROI
    coords = cv2.findNonZero(close)
    x,y,w,h = cv2.boundingRect(coords)
    cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
    crop = original[y:y+h, x:x+w]
    
    cv2.imshow('thresh', thresh)
    cv2.imshow('close', close)
    cv2.imshow('image', image)
    cv2.imshow('crop', crop)
    cv2.waitKey()
    

    07-28 02:19
    查看更多