簡體   English   中英

Python opencv在圖像上找到五邊形輪廓

[英]Python opencv find pentagon contour on image

我正在嘗試從簡單的附加圖像中讀取數字。

在此處輸入圖片說明

為此,我試圖找到包含數字的五邊形。 但是,當我嘗試使用 opencv findcontour 函數查找五邊形時,它沒有給出正確的值。 我用那個函數嘗試了各種排列。 這些都沒有奏效。

到目前為止,我嘗試過以下操作:

import cv2 as cv
import numpy as np

im = cv.imread(r'out.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 200, 255, 0)

contours, hierarchy = cv.findContours(thresh, cv.RETR_LIST  , cv.CHAIN_APPROX_SIMPLE)

for c in contours:
    print(len(c))

輸出:1 1 1 1 1 1 1 1 38 36 1 1 85 87 128 133 55 47 4 4 7 4 4 4

這都不是5,所以以上幾點不能是五邊形。

如果我犯了任何錯誤,你能幫我嗎?

你在正確的軌道上。 找到輪廓后,您需要使用cv2.approxPolyDP + cv2.arcLength執行輪廓近似。 您可以檢查cv2.approxPolyDP的返回值,這將為您提供多邊形曲線形狀的近似值。 如果這個值是 5,那么你可以假設它是一個五邊形。 這是一個簡單的方法:

  1. 獲取二值圖像。 加載圖像,灰度, 雙邊濾波器大津閾值

  2. 查找輪廓並執行輪廓近似。 使用cv2.findContours查找輪廓,然后執行輪廓近似。 如果輪廓通過此過濾器,我們使用cv2.boundingRect提取邊界矩形坐標,並使用 Numpy 切片提取/保存 ROI。


檢測到的 ROI 為青色

在此處輸入圖片說明

提取/保存的投資回報率

在此處輸入圖片說明

注意:有兩個 ROI 保存為單獨的圖像,但它們是相同的。

代碼

import cv2
import numpy as np

# Load image, grayscale, bilaterial filter, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.bilateralFilter(gray,9,75,75)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours, perform contour approximation, and extract ROI
ROI_num = 0
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    # If has 5 then its a pentagon
    if len(approx) == 5:
        x,y,w,h = cv2.boundingRect(approx)
        cv2.rectangle(image, (x, y), (x + w, y + h), (200,255,12), 2)
        ROI = original[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_num), ROI)
        ROI_num += 1

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

暫無
暫無

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

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