简体   繁体   English

尝试在 openCV Python 中的图像中捕获形状

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

i have the image shown below and i am attempting to just capture the Squares and place a green line around them any help or direction would be great.我有下面显示的图像,我正在尝试捕获正方形并在它们周围放置一条绿线,任何帮助或方向都会很棒。

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()

在此处输入图像描述

I don't know exactly what your problem is (are the contours wrong? Nothing is being drawn on the image? etc) but here are some guesses.我不确切知道您的问题是什么(轮廓是否错误?图像上没有绘制任何内容?等等),但这里有一些猜测。

To draw lines around the contours, it looks like you are currently using white (0,0,0) to outline it.要在轮廓周围绘制线条,看起来您当前正在使用白色 (0,0,0) 来勾勒它。 -1 is to draw all contours to see if you are getting any results. -1 是绘制所有轮廓以查看是否得到任何结果。

Also some cv2 functions are destructive so I never use img when I am creating the output image.还有一些 cv2 函数具有破坏性,所以我在创建 output 图像时从不使用 img。 I would imShow and drawContours on a copy of the original 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