【发布时间】:2021-11-10 14:09:45
【问题描述】:
我正在尝试获取图像中白边矩形的坐标。传统的方法是找到轮廓来找到图像中存在的所有矩形,但我只想得到某些边框颜色,如下图
如何仅使用 opencv 获取白色边框矩形的坐标? 对此非常有帮助的任何建议,谢谢
编辑:我尝试了guivi使用python给出的建议,如下所示
import cv2
import numpy as np
import random as rng
image = cv2.imread('strawberry.png')
threshold = 100
grayscale= cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
canny_output = cv2.Canny(grayscale, threshold, threshold * 2)
ret, thresh= cv2.threshold(grayscale,200,255,cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(canny_output,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
contours_poly = [None]*len(contours)
#boundRect = [None]*len(contours)
boundRect = list()
centers = [None]*len(contours)
radius = [None]*len(contours)
for i, c in enumerate(contours):
contours_poly[i] = cv2.approxPolyDP(c, 3, True)
if len(contours_poly[i]) == 4:
boundRect.append(cv2.boundingRect(contours_poly[i]))
#boundRect[i] = cv.boundingRect(contours_poly[i])
#centers[i], radius[i] = cv.minEnclosingCircle(contours_poly[i])
drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
print(len(boundRect))
#for i in range(len(contours)):
# color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
# cv.drawContours(drawing, contours_poly, i, color)
# cv.rectangle(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \
# (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)
#cv.circle(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)
for i in range(len(boundRect)):
if boundRect[i][2]/boundRect[i][3] > 2:
color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
cv2.rectangle(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \
(int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)
print(f'Rectangle X:{boundRect[i][0]}, Y:{boundRect[i][1]}, W:{boundRect[i][2]}, H:{boundRect[i][3]}')
【问题讨论】:
标签: python python-3.x opencv image-processing deep-learning