gpt4 book ai didi

python - 使用 Python opencv 显示识别的形状

转载 作者:太空宇宙 更新时间:2023-11-03 23:11:43 25 4
gpt4 key购买 nike

我还是 opencv 的新手,但我发现了一段代码,可以识别图像中的形状轮廓并指示它们的中心。唯一的问题是程序会显示一个轮廓和一个中心,用户必须关闭手动打开窗口,以便显示另一个形状的中心以及第一个形状。

有没有办法让一个窗口同时显示所有轮廓和形状中心?

这对我来说是一个很大的问题,因为我打算稍后用相机流替换图像。因此,如果有任何其他建议可以提高此代码的效率,我将不胜感激。

这是代码(最后两行是可疑的):

import argparse
import imutils
import cv2


image = cv2.imread("shapes3.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
# find contours in the thresholded image
cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]

# loop over the contours
for c in cnts:
print("1")
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# draw the contour and center of the shape on the image
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.circle(image, (cX, cY), 7, (229, 83, 0), -1)
cv2.putText(image, "center", (cX - 20, cY - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 59, 174), 2)

# show the image
cv2.imshow("Image", image) #displaying processed image
cv2.waitKey(0)

Link到源头

Example Image (将其重命名为 shapes3.png)

最佳答案

通过在 for 循环终止后显示图像解决了这个问题

# loop over the contours
for c in cnts:
print("1")
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# draw the contour and center of the shape on the image
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.circle(image, (cX, cY), 7, (229, 83, 0), -1)
cv2.putText(image, "center", (cX - 20, cY - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 59, 174), 2)
# show the image
cv2.imshow("Image", image) #displaying processed image
cv2.waitKey(0)

关于python - 使用 Python opencv 显示识别的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48849870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com