如何解决opencv从图像获取两个正方形的边界框
我想从图像中获取边界框。 我想要两个白框的坐标。 这是一个示例图像: 我尝试了
_a,_b,stats,_c = cv2.connectedComponentsWithStats(image,connectivity=8)
,然后这些框位于stats对象中。 但是我得到的图像超过了2个框。这很奇怪。
也许有人还有其他解决方案?
解决方法
尝试使用查找轮廓
contours,hierarchy = cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i,contour in enumerate(contours[1::]):
bbox = cv2.boundingRect(contour)
,
import cv2
# Read image
img = cv2.imread("/Users/sb/Desktop/7n8uq.png",cv2.IMREAD_COLOR)
# Convert to grayscale
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Threshold (Produces a binary image)
_,thresh = cv2.threshold(
img_gray,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite("thresh.png",thresh)
# Find contours
contours,hierarchy = cv2.findContours(
thresh,cv2.CHAIN_APPROX_SIMPLE)
print("Total number of contours: {}".format(len(contours)))
all_contours_drawn = cv2.drawContours(
img.copy(),contours,-1,(0,0),2) # draw all contours
cv2.imwrite("all_contours.png",all_contours_drawn)
box_center_x = []
box_center_y = []
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
box_center_x.append(x+w/2)
box_center_y.append(y+h/2)
print("x-coordinate of boxes: {}".format(box_center_x))
print("y-coordinate of boxes: {}".format(box_center_y))
# Draw box centers
all_box_centers_drawn = img.copy()
for i in range(len(box_center_x)):
cv2.circle(
all_box_centers_drawn,(int(box_center_x[i]),int(box_center_y[i])),2,255),2)
cv2.imwrite("box-centers.png",all_box_centers_drawn)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。