gitea_ap_art_assets/draw_line.py

38 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import cv2
import numpy as np
# 读取图像并将其转换为灰度图像
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 查找轮廓
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
for contour in contours:
# 计算轮廓长度
contour_length = cv2.arcLength(contour, True)
# 定义线条粗细的列表使其从1到10逐渐增加
thickness_list = np.linspace(1, 10, len(contour))
# 遍历轮廓上的每个点,并在图像中绘制线条
for i, point in enumerate(contour):
# 计算当前点的线条粗细
thickness = int(thickness_list[i])
# 绘制线条
if i == 0:
# 如果是起点线条粗细为1
cv2.circle(img, tuple(point[0]), 1, (0, 0, 255), -1)
else:
# 如果不是起点线条粗细为thickness
prev_point = tuple(contour[i - 1][0])
curr_point = tuple(point[0])
cv2.line(img, prev_point, curr_point, (0, 0, 255), thickness)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()