描绘照片的轮廓形状并保存
import cv2
from matplotlib import pyplot as plt
# 1.先找到轮廓
img = cv2.imread('E:\Python-workspace\OpenCV\OpenCV/beyond.png', 0)
_, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
image, conturs, hierarchy = cv2.findContours(thresh, 3, 2)
cnt = conturs[0]# 2.进行多边形逼近,得到多边形的角点
approx = cv2.approxPolyDP(cnt, 3, True)#True表示该照片的图形为封闭图形# 3.画出多边形
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
cv2.polylines(image, [approx], True, (0, 255, 0), 2)#(0, 255, 0)为绿色,来控制边缘的颜色
plt.imshow(image),plt.show()
cv2.imwrite("E:\Python-workspace\OpenCV\OpenCV/YY.png",image)#保存照片
cv2.destroyAllWindows()#退出
效果如下:
运行前:
运行中:
运行后: