Python红线画图片轮廓
时间: 2023-11-19 17:54:55 浏览: 32
Python中可以使用OpenCV库来画图片轮廓。具体步骤如下:
1. 读取图片并将其转换为灰度图像。
2. 对灰度图像进行二值化处理。
3. 使用cv.findContours()函数寻找轮廓。
4. 使用cv.drawContours()函数绘制轮廓。
如果想要画出红线代表的外接最小矩形,可以使用cv.minAreaRect()函数得到最小矩形的四个角点,然后使用cv.drawContours()函数绘制这个矩形。
以下是一个示例代码:
```
import cv2 as cv
import numpy as np
# 读取图片并将其转换为灰度图像
img = cv.imread("number.png")
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 对灰度图像进行二值化处理
ret, thresh = cv.threshold(gray_img, 127, 255, 0)
# 使用cv.findContours()函数寻找轮廓
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
# 使用cv.drawContours()函数绘制轮廓
image = cv.cvtColor(gray_img, cv.COLOR_GRAY2BGR)
cv.drawContours(image, contours, -1, (0, 0 , 255), 2)
# 使用cv.minAreaRect()函数得到最小矩形的四个角点
cnt = contours[0]
min_rect = cv.minAreaRect(cnt)
box = cv.boxPoints(min_rect)
box = np.int0(box)
# 使用cv.drawContours()函数绘制最小矩形
cv.drawContours(image, [box], 0, (0, 0, 255), 2)
# 显示图片
cv.imshow("image", image)
cv.waitKey(0)
cv.destroyAllWindows()
```