我有一張尺寸為 1000x1000(灰度)的影像。我想從一個白色的畫布開始,在畫布上一個一個地繪制像素值,然后用它創建一個視頻。我們怎樣才能做到這一點?
uj5u.com熱心網友回復:
有很多方法可以做到這一點。我只會展示兩種方式:
- 使用OpenCV及其內置
VideoWriter的 - 使用PIL/Pillow和
ffmpeg外部
你可以使用OpenCV和它VideoWriter這樣的:
#!/usr/bin/env python3
import numpy as np
import cv2
# Load image in greyscale
im = cv2.imread('paddington.png', cv2.IMREAD_GRAYSCALE)
h, w = im.shape
# Make empty white RGB canvas same size
# I don't think VideoWriter likes greyscale frames, only 3-channel ones
canvas = np.full((h,w,3), 255, np.uint8)
# Create video writer
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter("output.avi", fourcc, 30.0, im.shape)
cnt = 0
for y in range(h):
for x in range(w):
# Copy a grey pixel from image to RGB canvas
canvas[y,x,:] = im[y,x], im[y,x], im[y,x]
# Write every 100th frame to video to speed it up
if cnt % 100 == 0:
out.write(canvas)
# Count frames
cnt = 1
out.release()

或者,如果您喜歡 - 或無法安裝OpenCV - 您可以使用PIL/Pillow并ffmpeg像這樣獲得相同的結果:
#!/usr/bin/env python3
################################################################################
# Run like this:
#
# ./plotPaddington2.py | ffmpeg -y -f rawvideo -pix_fmt gray8 -video_size 400x400 -i - -c:v h264 -pix_fmt yuv420p video.mov
################################################################################
from PIL import Image
import sys
# Load image in greyscale
im = Image.open('paddington.png').convert('L')
h, w = im.size
# Make empty white canvas same size
canvas = Image.new('L', im.size, 'white')
cnt = 0
for y in range(h):
for x in range(w):
# Copy a pixel from image to canvas
canvas.putpixel((x,y), im.getpixel((x,y)))
# Write every 100th frame to video to speed it up
if cnt % 100 == 0:
sys.stdout.buffer.write(canvas.tobytes())
# Count frames
cnt = 1
然后,您可以將此腳本的輸出通過管道傳輸到ffmpeg(調整大小引數以匹配您的視頻:
./plotPaddington2.py | ffmpeg -y -f rawvideo -pix_fmt gray8 -video_size 400x400 -i - -c:v h264 -pix_fmt yuv420p video.mov
請注意,如果您有一個 1000x1000 像素的影像,并且為每個像素創建一個新的視頻幀,您將獲得 1,000,000 幀視頻。如果你顯示 30 幀/秒,這對于視頻來說是很正常的,你的視頻將需要 9 個小時才能完成......所以我每 100 幀繪制一次:
hours = WIDTH * HEIGHT / (30 fps * 3600 seconds/hr) = 9.2 hrs
uj5u.com熱心網友回復:
這是偽代碼,但可能會有所幫助:
# assume x is 2d array with image of interest
_x = np.zeros_like(x) # temp emptyarray
for i in range(x.shape[0]):
for j in range(x.shape[1]):
_x[i,j] = x[i,j] # copy data (fill the temp array gradually)
... # pass _x to plotting library
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490893.html
上一篇:OpenCVC 中的填孔過濾器
