kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (
5
,
5
))
mask = cv2.erode(mask, kernel, iterations=
1
)
mask = cv2.dilate(mask, kernel, iterations=
1
)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_contour =
max
(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(max_contour)
cv2.rectangle(img, (x, y), (x + w, y + h), (
0
,
255
,
0
),
2
)
cv2.imshow(
"Result"
, img)
cv2.waitKey(
0
)
请注意,此代码仅适用于图像中只有一个颜色块的情况。如果您想要检测多个颜色块,则需要调整代码以识别和绘制每个颜色块的矩形框。