调用cv2.findContours()函数实现轮廓检测,检测图像中物体的轮廓。 2、调用imutils.grab_contours()函数获取图像轮廓。 3、调用contours.sort_contours()函数将轮廓从左到右进行排序。 4、初始化比例系数pixelsPerMetric为空,用于后续真实长度计算。 5、初始化参照物宽度width为3,用于后续真实长度计算。python
时间: 2023-05-18 11:06:51 浏览: 162
非常好的问题!以下是代码示例:
```python
import cv2
import imutils
from imutils import contours
# 读取图像
image = cv2.imread("example.jpg")
# 灰度化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 边缘检测
edged = cv2.Canny(gray, 50, 100)
# 轮廓检测
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# 轮廓排序
(cnts, _) = contours.sort_contours(cnts)
# 初始化比例系数和参照物宽度
pixelsPerMetric = None
width = 3
# 真实长度计算
for c in cnts:
if cv2.contourArea(c) < 100:
continue
orig = image.copy()
box = cv2.minAreaRect(c)
box = cv2.boxPoints(box)
box = np.array(box, dtype="int")
box = perspective.order_points(box)
cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)
for (x, y) in box:
cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)
(tl, tr, br, bl) = box
(tltrX, tltrY) = midpoint(tl, tr)
(blbrX, blbrY) = midpoint(bl, br)
(tlblX, tlblY) = midpoint(tl, bl)
(trbrX, trbrY) = midpoint(tr, br)
cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)
dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))
if pixelsPerMetric is None:
pixelsPerMetric = dB / width
dimA = dA / pixelsPerMetric
dimB = dB / pixelsPerMetric
cv2.putText(orig, "{:.1f}in".format(dimA),
(int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,
0.65, (255, 255, 255), 2)
cv2.putText(orig, "{:.1f}in".format(dimB),
(int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
0.65, (255, 255, 255), 2)
cv2.imshow("Image", orig)
cv2.waitKey(0)
```
这段代码可以实现轮廓检测、轮廓排序和真实长度计算。
阅读全文