代码之家  ›  专栏  ›  技术社区  ›  Aadit

在python中使用PIL修剪图像中的空白

  •  1
  • Aadit  · 技术社区  · 7 年前

    我正在做 手写数字识别 使用 SciKit学习 为此,我需要裁剪单击的图片,以便我在Word上准备了一个模板。 现在我想要的是沿着边界裁剪图像,这样我可以进一步裁剪以提取数字。
    示例图像如下所示:

    enter image description here

    用于裁剪我使用的图像 this 密码

    下面是从中裁剪出上述矩形的父图像:
    enter image description here

    注意:父图像也有边框(在图像中不可见),因此修剪空白可能有助于获得修改的父图像,以便预定义的(高度、宽度)对于要在图像上进行的各种裁剪几乎相同。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Andriy Makukha    7 年前

    您可以应用此管道:转换为灰度->应用阈值(转换为白色和黑色)->查找等高线->选择正确形状的轮廓。

    下面是示例代码:

    #!/usr/bin/env python
    
    import cv2
    
    BLACK_THRESHOLD = 200
    THIN_THRESHOLD = 10
    ANNOTATION_COLOUR = (222,0,222)
    
    img = cv2.imread('template.png')
    orig = img.copy()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, thresh=BLACK_THRESHOLD, maxval=255, type=cv2.THRESH_BINARY_INV)[1]
    
    # Optional: save thesholded image
    cv2.imwrite("temp_thres.png", thresh)
    
    # Find contours on the thresholded image
    contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
    for cont in contours:
        # Find bounding rectangle of a contour
        x,y,w,h = cv2.boundingRect(cont)
        # Skip thin contours (vertical and horizontal lines)
        if h<THIN_THRESHOLD or w<THIN_THRESHOLD:
            continue
        # Does the countour has the right shape (roughly four times longer than high)?
        if 3*h<w<5*h:
            roi = orig[y:y+h,x:x+w]
            cv2.imwrite("four_letters.png",roi)
    
        # Optional: draw annotations
        cv2.rectangle(img,(x,y),(x+w,y+h),ANNOTATION_COLOUR,3)
    
    # Optional: save annotated image
    cv2.imwrite("temp_cont.png",img)
    

    (您可以删除这三个可选步骤。它们仅用于生成图像 temp_thres.png temp_cont.png .)

    输入图像 template.png :

    Input image: blank template

    阈值图像 温度\u thres。巴布亚新几内亚 :

    White and black thresholded image

    找到的等高线 temp\u cont.png :

    Original image with two regions annotated

    四字母空格 four_letters.png :

    Cropped four letter space