【问题标题】:OpenCV VideoWriter Fails to Write with Coordinates GivenOpenCV VideoWriter 无法使用给定的坐标写入
【发布时间】:2021-08-05 23:10:42
【问题描述】:

我正在开发一个屏幕录像机项目,在该项目中我使用 PIL 捕获帧。 如果我将 bbox 的坐标设置为 0 和 0,程序可以正常工作,但如果我改变它们,VideoWriter 函数什么也不写。这是我的代码:

import numpy as np
from PIL import ImageGrab as ig
import cv2
fcc=cv2.VideoWriter_fourcc('m','p','4','v')
output=cv2.VideoWriter('output.mp4',fcc,20.0,(500,500))
while 1:
    img=ig.grab(bbox=(20,20,500,500))
    imn=np.array(img)
    imf=cv2.cvtColor(imn,cv2.COLOR_BGR2RGB)
    cv2.imshow('Output',imf)
    output.write(imf)
    if cv2.waitKey(10)==ord('q'):
        break

【问题讨论】:

  • VideoWriter constructor 采用大小,而不是边界框。
  • 显然,输出文件的帧大小与 ImageGrab 的帧大小不匹配。我更新了代码,还是没有结果

标签: python numpy opencv python-imaging-library


【解决方案1】:

边界框的尺寸必须与视频帧大小相匹配。

cv2.VideoWriter设置的视频帧大小为(500,500)
边界框大小必须为 500x500。

bbox 元组格式为 (left_x, top_y, right_x, bottom_y) - 最后两个参数是 right_x 和 bottom_y 而不是宽度和高度(实际上是 right_x+1 和 bottom_y+1)。
请参阅:ImageGrab.grab(bbox) and Image.getpixel() Used together

正确的代码是:

img = ig.grab(bbox=(20, 20, 520, 520))

还有一个问题:

您必须致电output.release() 才能正确关闭录制的视频文件。


这是一个完整的代码示例:

import numpy as np
from PIL import ImageGrab as ig
import cv2

cols, rows = 500, 500

fcc = cv2.VideoWriter_fourcc('m','p','4','v')
output = cv2.VideoWriter('output.mp4', fcc, 20.0, (cols,rows))

while True:
    #img = ig.grab(bbox=(20,20,500,500))  #bbox = (left_x, top_y, right_x, bottom_y)

    # https://stackoverflow.com/questions/49479552/imagegrab-grabbbox-and-image-getpixel-used-together
    left_x = 20
    top_y = 20
    right_x = left_x + cols
    bottom_y = top_y + rows
    img = ig.grab(bbox=(left_x, top_y, right_x, bottom_y))

    imn = np.array(img)
    imf = cv2.cvtColor(imn, cv2.COLOR_BGR2RGB)
    cv2.imshow('Output', imf)
    output.write(imf)
    if cv2.waitKey(10)==ord('q'):
        break

output.release()
cv2.destroyAllWindows()

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2015-06-01
    • 2023-03-13
    • 2020-06-04
    • 2023-01-04
    相关资源
    最近更新 更多