Python& OPENCV:改进代码以进行对象检测和查找中心
我正在尝试编写一个代码以查找轮廓并提取边界矩形坐标,然后找到中心坐标并绘制中心点。但是我不喜欢代码执行的结果。
这是Python中的一个代码:
import cv2
import numpy as np
import imutils
image = cv2.imread('res.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray_image, (7,7) ,10)
thresh = cv2.threshold(blurred, 160, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
for c in cnts:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.circle(image, (cX, cY), 4, (255, 255, 255), -1)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
这是我现在得到的:
这是我希望得到的:
为什么我得到这样的结果?如何改进此代码?
I'm trying to write a code to find contours and extract the bounding rectangle coordinates, then find center coordinate and draw center point. But I don't like the result of code execution.
Here's a code in Python:
import cv2
import numpy as np
import imutils
image = cv2.imread('res.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray_image, (7,7) ,10)
thresh = cv2.threshold(blurred, 160, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
for c in cnts:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.circle(image, (cX, cY), 4, (255, 255, 255), -1)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
This is what I get now:
This is what I expect to get:
Why I get such result? How can I improve this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想要边界框的中心:
只是做:
质量中心并不总是是边界框的中心,因此,如果您想要边界框的中心,只需使用
cv2.boundingRect()
。似乎您正在使用
cv2.findContours
的标志没有返回任何轮廓。cv2.chain_approx_simple
更改为:
cv2.chain_approx_none
cv2.retr_external
更改为:
cv2.retr_list
还删除了
阈值
和blur
。检查 opencv文档。
https://i.sstatic.net/17kop.png
If you want the center of the bounding box:
Just do:
The center of mass is not always the center of bounding box so if you want the center of bounding box just use
cv2.boundingRect()
.Seems like the flag you were using for
cv2.findContours
was not returning any contour.cv2.CHAIN_APPROX_SIMPLE
Changed to:
cv2.CHAIN_APPROX_NONE
cv2.RETR_EXTERNAL
Changed to:
cv2.RETR_LIST
Also removed
threshold
andblur
.Check the OpenCV documentation.
https://i.sstatic.net/17kOp.png