如何在Python中按像素逐点绘制双正弦函数?
使用OpenCV逐点生成双正弦波形的简便方案
你目前用Matplotlib实现了逐点生成波形的动画,但OpenCV在像素级绘图和实时显示上更直接,不需要依赖Matplotlib的动画框架,下面是更简便的实现方案:
你的原Matplotlib代码
%matplotlib notebook import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from IPython.display import HTML amp = 0.5 # 1V (Amplitude) f = 20 frame_rate = 100 t = np.linspace(0, np.pi/2, 1000) x = np.sin(t) y = amp * (np.cos(2 * np.pi * f * t) + np.pi / 2) # pixel size in inches (width,height) dpi = 64 fig, ax = plt.subplots(figsize=(4, 4), dpi=dpi) line, = ax.step(x, y) plt.show() def animate(frame, x, y, line): line.set_data(x[:frame], y[:frame]) y_new = 0.5 * (np.cos(2 * np.pi * 20 * t[:frame]/2) + np.pi / 2) line.set_ydata(y_new) return line, interval = 1000 / frame_rate ani = FuncAnimation(fig, animate, frames=1000, interval=interval, fargs=[x, y, line]) HTML(ani.to_jshtml())
OpenCV实现代码
import numpy as np import cv2 # 画布参数(像素级) WIDTH, HEIGHT = 256, 256 # 对应原代码4*64=256像素尺寸 FPS = 100 DELAY = int(1000 / FPS) # 波形参数与坐标计算 total_points = 1000 t = np.linspace(0, np.pi/2, total_points) # 第一个正弦波形:将数值映射到画布像素坐标(留10像素边距避免超出) x1 = np.int32(np.sin(t) * (WIDTH - 20) + 10) y1 = np.int32(0.5 * (np.cos(2 * np.pi * 20 * t) + np.pi/2) * (HEIGHT - 20) + 10) # 第二个正弦波形(对应原代码animate中的y_new) x2 = x1 # 共用x轴坐标 y2 = np.int32(0.5 * (np.cos(2 * np.pi * 20 * t/2) + np.pi/2) * (HEIGHT - 20) + 10) # 初始化黑色画布 canvas = np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8) for i in range(total_points): # 清空画布(若要保留完整轨迹,注释此行即可) canvas.fill(0) # 逐点绘制第一个波形(绿色) for j in range(i+1): cv2.circle(canvas, (x1[j], y1[j]), 1, (0, 255, 0), -1) # 逐点绘制第二个波形(红色) for j in range(i+1): cv2.circle(canvas, (x2[j], y2[j]), 1, (0, 0, 255), -1) # 显示当前帧 cv2.imshow('Dual Sine Wave', canvas) # 控制帧率,按下ESC键可提前退出 if cv2.waitKey(DELAY) & 0xFF == 27: break # 清理窗口资源 cv2.destroyAllWindows()
代码解释
- 像素级直接映射:跳过Matplotlib的英寸-DPI转换,直接用像素尺寸定义画布,将三角函数计算结果直接映射为画布坐标,逻辑更直观。
- 极简动画逻辑:通过循环逐帧更新画布,用
cv2.waitKey控制帧率,不需要复杂的动画类或回调函数,代码结构更简洁。 - 灵活调整:若需要绘制连续线条而非单点,可将
cv2.circle替换为cv2.line连接相邻点;若要保留轨迹,只需注释掉清空画布的代码。
资源推荐
- OpenCV官方文档中的2D绘图模块:重点掌握
cv2.line、cv2.circle等基础像素绘制函数的用法。 - NumPy官方文档中的数组运算章节:学习如何高效将数学计算结果转换为符合画布要求的整数像素坐标。
内容的提问来源于stack exchange,提问作者www21
相关产品推荐
相关产品推荐

