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

标签 python opencv python-imaging-library

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

enter image description here

为了裁剪我正在使用的图像 this代码。

下面是裁剪了上面的矩形的父图像:
enter image description here

Note: The parent image has a border too(which is not visible in the image) so trimming the white space might help in getting a modified parent image so that predefined (height, width) would be almost same for various crops to be done on the image.

最佳答案

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

示例代码如下:

#!/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.pngtemp_cont.png。)

输入图片template.png:

Input image: blank template

阈值图像temp_thres.png:

White and black thresholded image

找到轮廓temp_cont.png:

Original image with two regions annotated

四字母空格four_letters.png:

Cropped four letter space

关于python - 在 python 中使用 PIL 修剪图像中的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49609062/

相关文章:

python - chalice 中缺少公钥文件

python - 现有演示文稿中每张 pptx 幻灯片的形状编号/索引

opencv - OpenCV帧延迟

python - 由于 textsize 弃用,尝试使用 Python PIL ImageDraw.textbbox 但出现错误

python - 使用 Python 将 Exif DMS 转换为 DD 地理定位

python - 无法根据规则 ('O' 将数组数据从 dtype ('float64' ) 转换为 dtype 'safe' )

python - pyLCIO setMomentum : error const float* in python

python - OpenCV cv2 图像到 PyGame 图像?

c++ - 是否可以创建和使用 MatIterator 数组?

python - 叠加图像并在每个像素位置显示较亮的像素