使用cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)时出错

问题描述 投票:1回答:1

[为了计算动画的每一帧中的白色像素数(白色圆圈在黑框上移动,我碰到了此OpenCV function

cap = cv2.VideoCapture('control_random.mp4')

total_white_pixels_in_video_sequence = 0

while(cap.isOpened()):

    # Take each frame of the video.
    _, frame = cap.read()


    #print(frame)

    # Convert BGR to gray
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    print ("No. of pixels : ", gray.shape[0] * gray.shape[1])

    # Counting the number of pixels with given value: define range of gray color in HSV
    total_white_pixels_in_video_sequence += np.count_nonzero(gray == 255)

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

print ("total_white_pixels_in_video_sequence : ", total_white_pixels_in_video_sequence)

我遇到第一个错误:

错误:OpenCV(4.1.0)/io/opencv/modules/imgproc/src/color.cpp:182:错误:(-215:断言失败)!_ src.empty()在函数“ cvtColor”中

我在这里找到此错误的两种可能的解决方案:

  1. 我尝试过gray = cv2.cvtColor(np.float32(frame), cv2.COLOR_BGR2GRAY),但仍然出现错误:

TypeError:参数'src'的预期cv :: UMat]

  1. 然后我尝试了gray = cv2.cvtColor(cv2.UMat(frame), cv2.COLOR_BGR2GRAY),并得到了错误:

[AttributeError:'cv2.UMat'对象没有属性'shape']

[打印框架时,我得到一个零数组:[[[0 0 0] [0 0 0] [0 0 0] ...

我检查了路径,它在此代码的同一目录中。所以路径应该不是问题吗?

我按照link的建议检查了视频文件的完整性,并在Linux终端中尝试了以下命令:ffmpeg -v error -i control_random.mp4 -f null - 2>error.log,但未打印任何内容。

我的问题:调试是否值得,或者还有另一种方法来计算每帧白色像素的数量。在创建动画时以及生成视频之前,我也可以这样做。

这段代码创建了我的动画:

for Nframes in range(8):

    with shader:  

        transformations['view_matrix'] = get_view_matrix(z=scrDist)
        transformations.send()


        for sphere in spheres:

            # Update Spheres Positions
            sphere.position.x += sphere.dx
            sphere.position.y += sphere.dy
            sphere.position.z += sphere.dz

            # Draw the spheres
            sphere.draw()

    # Get the back buffer frames
    win.getMovieFrame(buffer='back')

    win.flip()

非常感谢您的帮助,我们迫切需要它。非常感谢!

python opencv pixel video-processing
1个回答
2
投票

我的猜测是您在不同时间点都有此错误,这就是令人困惑的地方。原始错误可能发生在视频结尾。

© www.soinside.com 2019 - 2024. All rights reserved.