簡體   English   中英

如何使用 Python OpenCV 在圖像中查找單個數字?

[英]How to find individual numbers in an image with Python OpenCV?

我有一個類似於以下的圖像。 我想分開兩個數字74 ,如圖所示,因為我想為這兩個對象中的每一個設置一個邊界框。

在此處輸入圖像描述

我怎么能用 OpenCV 做到這一點? 我不知道,我怎么能這樣做,並且正在考慮是否有某種方法可以使用 Sobel 運算符。 我唯一厭倦的就是得到索貝爾。

s = cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)

在此處輸入圖像描述

但不知道如何從這里開始。

對圖像中的圖形進行分割和檢測,主要思想如下:

  1. 使用cv2.cvtColor()將圖像轉換為灰度
  2. cv2.GaussianBlur()模糊圖像
  3. 使用cv2.Canny()查找邊緣
  4. 使用 cv2.findContours() 查找輪廓並使用cv2.findContours() imutils.contours.sort_contours()排序,以確保當我們遍歷輪廓時,它們的順序正確
  5. 遍歷每個輪廓
    • 使用cv2.boundingRect()獲取邊界矩形
    • 使用 Numpy 切片查找每個輪廓的 ROI
    • 使用cv2.rectangle()繪制邊界框矩形

Canny 邊緣檢測

在此處輸入圖像描述

檢測到的輪廓

在此處輸入圖像描述

裁剪和保存的 ROI

在此處輸入圖像描述

輸出

Contours Detected: 2

代碼

import numpy as np
import cv2
from imutils import contours

# Load image, grayscale, Gaussian blur, Canny edge detection
image = cv2.imread("1.png")
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)

# Find contours and extract ROI
ROI_number = 0
cnts = cv2.findContours(canny, 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")
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    ROI = original[y:y+h, x:x+w]
    cv2.rectangle(image, (x,y), (x+w,y+h),(36, 255, 12), 3)
    cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
    ROI_number += 1

print('Contours Detected: {}'.format(ROI_number))
cv2.imshow("image", image) 
cv2.imshow("canny", canny)
cv2.waitKey()

按照步驟:

  1. 將圖像轉換為灰度。
  2. 使用閾值將圖像轉換為二進制圖像,在您的問題中,我認為自適應高斯將最有益於使用。
  3. 應用輪廓檢測​​,然后您可以在輪廓周圍制作邊界框。

您可能需要根據大小或位置過濾輪廓。

暫無
暫無

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

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