如何分割图像中的两个矩形。还可以通过删除额外的投影来提取矩形的坐标。轮廓检测将整个图像显示为一个圆形,而不是将其分成两个矩形。
请找到输入图像,
检测形状.py
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
sd = ShapeDetector()
for c in cnts:
M = cv2.moments(c)
cX = int((M["m10"] / M["m00"]))
cY = int((M["m01"] / M["m00"]))
shape = sd.detect(c)
c = c.astype("float")
#c *= ratio
c = c.astype("int")
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (255, 0, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
形状检测器.py
class ShapeDetector:
def __init__(self):
pass
def detect(self, c):
shape = "unidentified"
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
if len(approx) == 3:
shape = "triangle"
elif len(approx) == 4:
print("value of approx", approx)
(x, y, w, h) = cv2.boundingRect(approx)
ar = w / float(h)
print("value of ar",ar)
if (ar >= 0.95 and ar <= 1.05): shape = "Square"
elif (ar <= 5 and ar >= 3): shape = "Obround"
else: shape = "rectangle"
elif len(approx) == 5:
shape = "pentagon"
elif len(approx) == 2:
shape = "line"
print("value of approx", approx)
else:
shape = "circle"
print("value of approx", approx)
return shape