OpenCV VideoWriter 无法使用给定的坐标写入
OpenCV VideoWriter Fails to Write with Coordinates Given
我正在做一个屏幕录像机项目,我在其中使用 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
边界框的尺寸必须与视频帧尺寸匹配。
cv2.VideoWriter
设置的视频帧大小为(500,500)
。
边界框大小必须为 500x500。
bbox
元组格式是 (left_x, top_y, right_x, bottom_y)
- 最后两个参数是 right_x 和 bottom_y 而不是宽度和高度(实际上是 right_x+1和 bottom_y+1).
参见:.
正确的代码是:
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)
#
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()
我正在做一个屏幕录像机项目,我在其中使用 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
边界框的尺寸必须与视频帧尺寸匹配。
cv2.VideoWriter
设置的视频帧大小为(500,500)
。
边界框大小必须为 500x500。
bbox
元组格式是 (left_x, top_y, right_x, bottom_y)
- 最后两个参数是 right_x 和 bottom_y 而不是宽度和高度(实际上是 right_x+1和 bottom_y+1).
参见:
正确的代码是:
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)
#
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()