视频帧灰度化线程处理报错:Line2D.set()收到意外'cmap'参数
问题描述
运行线程分割视频帧并转为灰度图的代码时,出现以下错误:
文件路径"C:\Users\USER\PycharmProjects\ASCIIPICproject\venv\lib\site-packages\matplotlib\artist.py"第1160行,在_update_props中抛出AttributeError:Line2D.set() got an unexpected keyword argument 'cmap'
对应的过滤线程函数代码:
def saveFramesFiltered(): currentFrame = 0 framemax = 215 while currentFrame < framemax: while not os.path.exists("./framesBefore/frame" + str(currentFrame) + '.jpg'): time.sleep(0.01) lock.acquire() image = pltim.imread("./framesBefore/frame" + str(currentFrame) + '.jpg') lock.release() r, g, b = image[:, :, 0], image[:, :, 1], image[:, :, 2] grayImage = 0.299 * r + 0.587 * g + 0.114 * b plt.plot(grayImage, cmap="gray") plt.axis("off") lock.acquire() plt.savefig("./framesAfter/grayImage" + str(currentFrame) + ".jpg", bbox_inches='tight', pad_inches=0) lock.release() time.sleep(0.01)
问题原因与修复方案
错误原因:
plt.plot()是绘制折线图的函数,不支持cmap(颜色映射)参数,处理图像应该用专门的plt.imshow()函数。另外原代码遗漏了帧计数递增,会导致无限循环,且未关闭画布可能引发内存泄漏。修正后的代码:
import os import time import matplotlib.pyplot as plt def saveFramesFiltered(): currentFrame = 0 framemax = 215 while currentFrame < framemax: frame_path = f"./framesBefore/frame{currentFrame}.jpg" while not os.path.exists(frame_path): time.sleep(0.01) lock.acquire() image = plt.imread(frame_path) # 修正笔误pltim为plt lock.release() # 计算灰度图(兼容RGB和已灰度化的图像) if len(image.shape) == 3: r, g, b = image[:, :, 0], image[:, :, 1], image[:, :, 2] grayImage = 0.299 * r + 0.587 * g + 0.114 * b else: grayImage = image # 用imshow替代plot显示灰度图 plt.imshow(grayImage, cmap="gray", interpolation="none") plt.axis("off") lock.acquire() plt.savefig(f"./framesAfter/grayImage{currentFrame}.jpg", bbox_inches='tight', pad_inches=0) lock.release() plt.close() # 关闭画布释放内存 currentFrame += 1 # 递增帧计数,避免无限循环 time.sleep(0.01)
内容的提问来源于stack exchange,提问作者MR. potato35
相关产品推荐
相关产品推荐

