擅长:python、mysql、java
<p>只要得到轮廓,然后找到边界矩形。检查官方文件中的<a href="https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html" rel="nofollow noreferrer">this tutorial</a>。在</p>
<pre><code>import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_NONE)
x1, y1, w, h = cv2.boundingRect(contours[0])
x2, y2 = x1 + w, y1 + h
print((x1, y1), (x2, y2))
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imwrite('res.jpg', img)
</code></pre>
<p>矩形左上、右下点坐标(<em>(x1,y1),(x2,y2)</em>):</p>
^{pr2}$
<p>结果:</p>
<p><a href="https://i.stack.imgur.com/D6hbu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D6hbu.jpg" alt="res.jpg"/></a></p>