OpenCV python 绘制图像轮廓
处理原图:[source.jpg]
import cv2
import numpy as np
def main():
# 1.导入图片
img_src = cv2.imread("source.jpg")
# 绘制图片
# img_src = np.zeros([500, 500, 3], dtype=np.uint8)
#
# cv2.rectangle(img_src, (80, 80), (200, 200), (255, 255, 255), -1)
# cv2.circle(img_src, (300, 350), 50, (255, 255, 255), -1)
#
# points = np.array([[350, 50], [450, 160], [300, 150]], np.int32)
# points = points.reshape((-1, 1, 2))
#
# cv2.polylines(img_src, [points], True, (255, 255, 255), 8)
# 2.灰度处理与二值化
img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
# 3.连通域分析
img_contour, contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# 4.绘制连通域外框
img_result = img_src.copy()
cv2.drawContours(img_result, contours, -1, (0, 0, 255), 5)
# 5.显示结果
cv2.imshow("img_src", img_src)
cv2.imshow("img_result", img_result)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
结果图片:[img_result.jpg]