簡體   English   中英

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

[英]Trimming the white space in an image using PIL in python

我正在使用SciKit-learn進行手寫數字識別,因此我需要裁剪單擊的圖片,因此我在Word上准備了模板。 現在我想要的是沿着邊框裁剪圖像,以便可以進一步裁剪以提取數字。
示例圖片如下:

在此處輸入圖片說明

為了裁剪圖像,我正在使用代碼。

下面是裁剪了上面矩形的父圖像:
在此處輸入圖片說明

注意:父圖像也有邊框(在圖像中不可見),因此修剪空白可能有助於獲取修改后的父圖像,以便對要進行的各種作物的預定義(高度,寬度)幾乎相同圖片。

您可以應用此管道:轉換為灰度->應用閾值處理(轉換為白色和黑色)->查找輪廓->選擇正確形狀的輪廓。

這是示例代碼:

#!/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

輸入圖像:空白模板

閾值圖像temp_thres.png

黑白閾值圖像

找到輪廓temp_cont.png

帶有兩個區域的原始圖像

四個字母的空間four_letters.png

裁剪四個字母的空間

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM