[Python] How to average number of frames in OpenCV2

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I found this very nice example, how to make an array of frames: https://stackoverflow.com/a/17394994/7489698

    But I do not know how to use this in PIL correctly. To demonstrate it, I have sketched this commands:

    import numpy as np
    import cv2
    from PIL import Image, ImageTk

    nframes = 10
    frame = cv2.imread('test.jpg')

    (x,y,d)=frame.shape
    frames = np.empty((nframes,x, y, d))

    for k in range(nframes):
    frames[k,:,:,:] = frame

    frame_avg=np.int8(np.mean(frames,0))
    frame_avg.shape

    cv2.imwrite('test_avg.jpg',frame_avg)

    Image.fromarray(frame)
    Image.fromarray(frame_avg)


    The image test.jpg is read and 10 times stored in the array frames. The average thereof is stored in the file test_avg.jpg where it can be seen that it looks ok.

    Converting the orignal frame to a PIL image is working, but the last line throws this error:

    ---> 20 Image.fromarray(frame_avg)

    /usr/local/lib/python3.10/dist-packages/PIL/Image.py in fromarray(obj, mode)
    3313 typekey_shape, typestr = typekey
    3314 msg = f"Cannot handle this data type: {typekey_shape}, {typestr}"
    -> 3315 raise TypeError(msg) from e
    3316 else:
    3317 rawmode = mode

    TypeError: Cannot handle this data type: (1, 1, 3), |i1


    What did I do wrong???

    KR, Christof

    Continue reading...

Compartilhe esta Página