查找视频中红色和蓝色值的均值和标准差

Find mean and sd of red and blue colour values in video

我有视频文件可以转换为 RGB space,每帧 cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

然后我想计算红色和蓝色值的平均值和标准偏差,在 100 秒的时间段内进行平均和标准偏差。我的视频超过 100 秒长,因此希望每 100 秒重复一次并将值分配给向量。 因此,对于每第 n 个 100 秒剪辑,我都有值 R(ave)、R(sd)、B(ave)、B(sd)。

我对 CV 和视频处理还很陌生,因此希望能在这方面提供任何帮助。

终于写出来了。对于超过 1 分钟的视频,整个程序将 运行 足够长。而且,如果您的计算机性能较差,那么我不会羡慕您。但总的来说它运作良好。这是:

import cv2


def calc_sd(arr: list, mean_val: float):
    prev_dis = 0
    for k in arr:
        prev_dis += (k - mean_val) ** 2
    dis = prev_dis / len(arr)
    return dis ** (1 / 2)


def calc_mean(arr: list):
    return sum(arr) / len(arr)


# list of your videos here
lst_of_videos = ['vid_test.mkv', 'signs.mkv', 'signs_ml.mkv']
lst_of_all_videos_data = []

for i in lst_of_videos:
    cap = cv2.VideoCapture(i)

    # list for data every 100 sec
    # data there will be like:
    # [['mean_red', 'mean_green', 'mean_blue', 'sd_red', 'sd_green', 'sd_blue'], 'and every 100 sec like this']
    lst_of_data = []

    lst_of_red = []
    lst_of_green = []
    lst_of_blue = []

    # getting video fps
    fps = cap.get(cv2.CAP_PROP_FPS)
    abstract_seconds = 0  # for counting frames

    print('video: ', i)

    while True:
        ret, frame = cap.read()

        if abstract_seconds >= 100 or not ret:
            print(' video: ', i, ', 100 secs, ret: ', ret)
            mean_red = calc_mean(lst_of_red)
            mean_green = calc_mean(lst_of_green)
            mean_blue = calc_mean(lst_of_blue)
            print('  mean counted')

            sd_red = calc_sd(lst_of_red, mean_red)
            sd_green = calc_sd(lst_of_green, mean_green)
            sd_blue = calc_sd(lst_of_blue, mean_blue)
            print('  sd counted')

            lst_of_data.append([mean_red, mean_green, mean_blue, sd_red, sd_green, sd_blue])
            lst_of_red.clear()
            lst_of_green.clear()
            lst_of_blue.clear()
            print('  arrays cleared')

            if not ret:
                break

        b, g, r = cv2.split(frame)
        lst_of_red.append(r.sum(axis=0).sum(axis=0) / r.size)
        lst_of_green.append(g.sum(axis=0).sum(axis=0) / g.size)
        lst_of_blue.append(b.sum(axis=0).sum(axis=0) / b.size)

        abstract_seconds += 1 / fps

    print(lst_of_data)
    lst_of_all_videos_data.append(lst_of_data)
    lst_of_data.clear()