def draw_pic(lab_txt,points,width= 1200, height = 1000):
left_margin = right_margin = 50
top_margin = bottom_margin = 50
# 计算绘图区域尺寸
plot_width = width - left_margin - right_margin
plot_height = height - top_margin - bottom_margin
# 提取坐标并计算范围
x = [p[0] for p in points]
y = [p[1] for p in points]
x_min, x_max = min(x), max(x)
y_min, y_max = min(y), max(y)
# 处理单一值情况
if x_max == x_min:
x_max += 1
if y_max == y_min:
y_max += 1
# 创建白色背景图像
img = np.full((height, width, 3), 255, dtype=np.uint8)
# 绘制坐标轴
cv2.line(img, (left_margin, height - bottom_margin),
(width - right_margin, height - bottom_margin), (0, 0, 0), 2)
cv2.line(img, (left_margin, height - bottom_margin),
(left_margin, top_margin), (0, 0, 0), 2)
# 绘制刻度线和标签
num_ticks = 5
x_ticks = np.linspace(x_min, x_max, num_ticks)
y_ticks = np.linspace(y_min, y_max, num_ticks)
# X轴刻度
for tick in x_ticks:
x_pos = int(left_margin + (tick - x_min)/(x_max - x_min)*plot_width)
y_pos = height - bottom_margin
cv2.line(img, (x_pos, y_pos), (x_pos, y_pos + 10), (0, 0, 0), 1)
label = f"{tick:.1f}"
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)
cv2.putText(img, label, (x_pos - tw//2, y_pos + 20 + th),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1)
# Y轴刻度
for tick in y_ticks:
y_pos = int(height - bottom_margin - (tick - y_min)/(y_max - y_min)*plot_height)
cv2.line(img, (left_margin - 10, y_pos), (left_margin, y_pos), (0, 0, 0), 1)
label = f"{tick:.1f}"
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)
cv2.putText(img, label, (left_margin - 15 - tw, y_pos + th//2),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1)
# 绘制数据点
prev_point = None
for data_i, (x_val, y_val) in enumerate(points):
x_pos = int(left_margin + (x_val - x_min)/(x_max - x_min)*plot_width)
y_pos = int(height - bottom_margin - (y_val - y_min)/(y_max - y_min)*plot_height)
cv2.circle(img, (x_pos, y_pos), 2, (0, 0, 255), -1, cv2.LINE_AA)
point=(x_pos, y_pos)
if prev_point is not None:
cv2.line(img, prev_point, point, (0, 255, 0), 1, cv2.LINE_AA)
prev_point=point
font_size=0.5
# 添加标签和标题
cv2.putText(img, lab_txt, (width//2 - 60, 30),
cv2.FONT_HERSHEY_SIMPLEX, font_size+0.2, (0, 0, 0), 2)
cv2.putText(img, "X Axis", (width//2 - 30, height - 15),
cv2.FONT_HERSHEY_SIMPLEX, font_size, (0, 0, 0), 1)
cv2.putText(img, "Y Axis", (15, height//2 - 20),
cv2.FONT_HERSHEY_SIMPLEX, font_size, (0, 0, 0), 1)
return img