簡體   English   中英

嘗試在 openCV Python 中的圖像中捕獲形狀

[英]Trying to Capture Shapes in an image in openCV Python

我有下面顯示的圖像,我正在嘗試捕獲正方形並在它們周圍放置一條綠線,任何幫助或方向都會很棒。

import numpy as np
import cv2

img = cv2.imread('beef.png')
imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret , thrash = cv2.threshold(imgGry, 240 , 255, cv2.CHAIN_APPROX_NONE)
contours , hierarchy = cv2.findContours(thrash, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

for contour in contours:
approx = cv2.approxPolyDP(contour, 0.01* cv2.arcLength(contour, True), True)
cv2.drawContours(img, [approx], 0, (0, 0, 0), 5)
x = approx.ravel()[0]
y = approx.ravel()[1] - 5
x, y , w, h = cv2.boundingRect(approx)
aspectRatio = float(w)/h
print(aspectRatio)

if aspectRatio >= 0.95 and aspectRatio < 1.05:
cv2.putText(img, "square", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))

else:
cv2.putText(img, "rectangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))

cv2.imshow('shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

在此處輸入圖像描述

我不確切知道您的問題是什么(輪廓是否錯誤?圖像上沒有繪制任何內容?等等),但這里有一些猜測。

要在輪廓周圍繪制線條,看起來您當前正在使用白色 (0,0,0) 來勾勒它。 -1 是繪制所有輪廓以查看是否得到任何結果。

還有一些 cv2 函數具有破壞性,所以我在創建 output 圖像時從不使用 img。 我會在原始 img 的副本上進行 imShow 和 drawContours。

cv2.drawContours(img, contours, -1, GREEN, 5)

暫無
暫無

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

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