【问题标题】:Remove image borders containing text in python在python中删除包含文本的图像边框
【发布时间】:2021-12-18 19:47:39
【问题描述】:

我有一张图像是某些移动扫描仪的输出。当来自移动扫描仪应用程序的图像时,图像被放置在一个矩形框内,并且边框具有扫描仪应用程序的 advt / 信息。以下是图片: 在上图中,“由 TapScanner 扫描”是广告信息。我从 stackoverflow 获得了删除图像边框的代码,它能够从顶部删除边框,但由于下部的文本,它无法从下方删除边框。 以下是代码:

from PIL import Image, ImageChops
def trim(image_path):
    im = Image.open(image_path)
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)
crop_image = trim(image_path)

以下是当前输出: 是否可以仅从整个图像中获取实际图像。请帮忙。我是图像处理的新手。 谢谢。

【问题讨论】:

    标签: python opencv python-imaging-library scikit-image opencv-python


    【解决方案1】:

    对图像设置阈值,并找到图像中最大的对象。

    #!/usr/bin/env python
    """
    Find and isolate the largest object in an image.
    """
    import matplotlib.pyplot as plt
    from skimage.io import imread
    from skimage.measure import label, regionprops
    
    figure, axes = plt.subplots(1, 3, sharex=True, sharey=True)
    
    raw = imread('cheque.jpg')
    axes[0].imshow(raw)
    
    threshold = 250 # might need adjustment
    binary = raw.mean(-1) < threshold
    axes[1].imshow(binary, cmap='gray')
    
    labeled = label(binary)
    regions = regionprops(labeled)
    
    largest = regions[0] # regions are ordered by area
    minr, minc, maxr, maxc = largest.bbox
    bx = (minc, maxc, maxc, minc, minc)
    by = (minr, minr, maxr, maxr, minr)
    
    axes[2].imshow(raw)
    axes[2].plot(bx, by, '-b', linewidth=2.5)
    
    for ax in axes:
        ax.axis([0, raw.shape[1], raw.shape[0], 0])
    
    new = raw[minr:maxr, minc:maxc]
    fig, ax = plt.subplots()
    ax.imshow(new)
    
    plt.show()
    

    【讨论】:

    • 谢谢@paul。但是您的解决方案不适用于其他图像。我找到了一个解决方案,并且正在为我的大部分图像工作。您可以找到解决方案here
    【解决方案2】:

    经过一番搜索,我找到了一个不错的解决方案,如下:

    import opencv2
    image = cv2.imread('cheque.jpg')
    
    # convert to gray scale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # detect edges uing canny
    edged = cv2.Canny(gray, 1, 1)
    
    # find the countours
    contours, hierarchy = cv2.findContours(edged, 
        cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    
    # take the maximum counter using "length" instead of "area"
    contour = max(contours, key=len)
    
    # get the edges of the counter
    x, y, w, h = cv2.boundingRect(contour)
    
    # crop the counter and save it
    roi = image[y:y+h, x:x+w]
    cv2.imwrite('cheque-crop.jpg', roi)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 2013-09-05
      • 2011-08-26
      相关资源
      最近更新 更多