首页 > 解决方案 > Python - 计算图像平均颜色的最快方法

问题描述

我正在尝试编写一个脚本来每秒从电影中获取一帧的平均颜色。目前我正在使用 Pillows resize() 函数执行此操作,但是它非常慢(每秒 5-10 帧),这意味着分析整部电影需要几个小时。这是我写的代码:

def analyse_frames(movie_path):
    try:
        with open(MOVIE_TITLE, "w") as file:
            counter = 0
            video = cv2.VideoCapture(movie_path)
            total_seconds = int(video.get(
                cv2.CAP_PROP_FRAME_COUNT)/video.get(cv2.CAP_PROP_FPS))
            succeeded, frame = video.read()
            while succeeded:
                video.set(cv2.CAP_PROP_POS_MSEC, (counter*1000))
                succeeded, frame = video.read()
                img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img_pil = Image.fromarray(img).resize((1, 1))
                color = str(img_pil.getpixel((0, 0)))[1:-1]
                file.write((str(color) + "\n"))
                counter += 1
                succeeded = counter <= total_seconds
                print(f"Frames analyzed: {counter} / {total_seconds}")
    except:
        print("Couldn't read movie file.")

有谁知道计算这个平均值的更快方法?任何帮助,将不胜感激!

标签: pythonopencvpython-imaging-library

解决方案


frame.mean(axis=(0,1))

假设它是一个 3 通道 numpy 数组,则为您提供该帧的平均 BGR(或 RGB)值。


推荐阅读