簡體   English   中英

如何使用 Python OpenCV 裁剪圖像上的每個字符?

[英]How to crop each character on an image using Python OpenCV?

我已經生成了這樣的 OpenCV 圖像

在此處輸入圖像描述

從最后一行代碼開始,如何分別裁剪和顯示當前圖像中的每個字符?

代碼

    labels = measure.label(thresh, connectivity=2, background=0)
    charCandidates = np.zeros(thresh.shape, dtype="uint8")

    for label in np.unique(labels):

        if label == 0:
            continue

        labelMask = np.zeros(thresh.shape, dtype="uint8")
        labelMask[labels == label] = 255
        cnts = cv2.findContours(labelMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)

        if len(cnts) > 0:
            c = max(cnts, key=cv2.contourArea)
            (boxX, boxY, boxW, boxH) = cv2.boundingRect(c)

            aspectRatio = boxW / float(boxH)
            solidity = cv2.contourArea(c) / float(boxW * boxH)
            heightRatio = boxH / float(crop_frame.shape[0])

            keepAspectRatio = aspectRatio < 1.0
            keepSolidity = solidity > 0.15
            keepHeight = heightRatio > 0.4 and heightRatio < 0.95


        if keepAspectRatio and keepSolidity and keepHeight:
            hull = cv2.convexHull(c)
            cv2.drawContours(charCandidates, [hull], -1, 255, -1)

    charCandidates = segmentation.clear_border(charCandidates)
    cnts = cv2.findContours(charCandidates.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cv2.imshow("Original Candidates", charCandidates)

    thresh = cv2.bitwise_and(thresh, thresh, mask=charCandidates)
    cv2.imshow("Char Threshold", thresh)

非常感謝。

這是一個簡單的方法:

  • 轉換為灰度
  • 大津的門檻
  • 查找等高線,從左到右對等高線進行排序,並使用等高線區域進行過濾
  • 提取投資回報率

在 Otsu 閾值化以獲得二值圖像后,我們使用imutils.contours.sort_contours()從左到右對輪廓進行排序。 這確保當我們遍歷每個輪廓時,我們以正確的順序獲得每個字符。 此外,我們使用最小閾值區域進行過濾以去除小噪聲。 這是檢測到的字符

在此處輸入圖片說明

我們可以使用 Numpy 切片提取每個字符。 這是每個保存的角色投資回報率

在此處輸入圖片說明

import cv2
from imutils import contours

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]

# Find contours, sort from left-to-right, then crop
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts, _ = contours.sort_contours(cnts, method="left-to-right")

ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area > 10:
        x,y,w,h = cv2.boundingRect(c)
        ROI = 255 - image[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()

暫無
暫無

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

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