我设法这样做:我找到了所有轮廓的层次结构,然后找到了 4 个具有相同层次结构编号的轮廓。这 4 个轮廓就是图中的 4 个正方形。
for cnt in zip(contours, hierarchy):
approx = cv2.approxPolyDP(cnt[0], 0.01 * cv2.arcLength(cnt[0], True), True)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(cnt[0])
ratio = float(w) / h
#print(cnt[1])
if 0.9 <= ratio <= 1.1:
correct_contours.append(cnt[1].tolist())
hierarchy_values = []
for array in correct_contours:
hierarchy_values.append(array[3])
value_counts = Counter(hierarchy_values)
values_occuring_exactly_four_times = [value for value, count in value_counts.items() if count == 4 and value != 0]
for cnt in zip(contours, hierarchy):
approx = cv2.approxPolyDP(cnt[0], 0.01 * cv2.arcLength(cnt[0], True), True)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(cnt[0])
ratio = float(w) / h
#print(cnt[1])
if 0.9 <= ratio <= 1.1:
if cnt[1][3] == values_occuring_exactly_four_times[0]:
cv2.putText(frame, 'Correct', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36, 255, 12), 2)
Moments = cv2.moments(cnt[0])
xCenter = int(Moments["m10"] / Moments["m00"])
yCenter = int(Moments["m01"] / Moments["m00"])
yValues.append(yCenter)
xValues.append(xCenter)
detected_squares.append(approx)
cv2.drawContours(frame, detected_squares, -1, (0,255, 0), 2)
cv2.imshow('image with drawn contours', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()