OpenCV Python移动垂直条纹动画重置卡顿问题修复咨询
修复移动垂直条纹动画的断层问题
问题原因
你的代码在条纹移位跨图像边界时,使用start_x:end_x切片赋值会因为start_x > end_x导致切片无效,这部分条纹无法被绘制,从而出现断层。同时,每次循环未重置图像背景,残留的旧像素也会干扰动画流畅度。
修复方案
- 每帧重置图像背景:避免旧帧像素残留影响新帧绘制效果。
- 处理跨边界条纹绘制:当条纹起始位置超出图像宽度时,将条纹拆分为两部分绘制——从起始点到图像右边界,以及从图像左边界到结束点。
修改后的完整代码
import numpy as np import cv2 def Vstripes(width, height, num_stripes, color1, color2, speed): stripe_width = width // num_stripes start_shift = 0 while True: # 每次循环重置为白色背景 image = np.ones((height, width, 3), dtype=np.uint8) * 255 for i in range(num_stripes): start_x = i * stripe_width + start_shift end_x = start_x + stripe_width color = color1 if i % 2 == 0 else color2 # 处理跨边界的条纹 if end_x > width: # 绘制从start_x到图像右边界的部分 image[:, start_x:width, :] = color # 绘制从图像左边界到剩余部分的部分 image[:, 0:(end_x - width), :] = color else: # 正常绘制不跨边界的条纹 image[:, start_x:end_x, :] = color cv2.imshow("Moving Vertical Stripes", image) key = cv2.waitKey(50) if key != -1: break # 更新移位,仅对图像宽度取模即可完成周期循环 start_shift = (start_shift + speed) % width cv2.destroyAllWindows() # 参数设置 width = 800 height = 600 num_stripes = 10 color1 = (255, 0, 0) # 蓝色 color2 = (0, 0, 0) # 黑色 speed = 1 # 移动速度 Vstripes(width, height, num_stripes, color1, color2, speed)
关键修改说明
- 将图像初始化移入循环内部,确保每帧都从干净的背景开始绘制。
- 移除了冗余的
% width计算,改为直接判断条纹是否跨边界并拆分绘制逻辑。 - 调整
start_shift的取模范围为width,因为总条纹宽度等于图像宽度,移位超过图像宽度即完成一个循环周期。
内容的提问来源于stack exchange,提问作者nep
相关产品推荐
相关产品推荐

