python - 如何从视频中获取 RGB 值?
问题描述
我想获取视频的 RGB 值并将其放入带有帧(帧,rgb 值)的二维数组中,并将其保存在文件中。我只找到了一种在图像像素上获取它的方法,并且不知道如何将数组保存在文件中。
from PIL import Image
im = Image.open("D:\swim\Frames1\Frames1.png")
pix=im.load()
width, height = im.size
pixels = [pix[i, j] for i in range(width) for j in range(height)]
print (pixels)
总之:我想加载视频并将其转换为由帧组成的数组,RGB 可能吗?
我努力了
from numpy import asarray
from numpy import savetxt
import cv2
cap = cv2.VideoCapture('D:\swim\swim99.mp4')
rgb_list = []
while True:
ret, frame = cap.read()
if not ret:
break
rgb_frame_i = frame.reshape(-1, 3).tolist()
rgb_list.extend(rgb_frame_i)
print(rgb_frame_i)
但它没有打印任何东西,我不知道如何将它保存在文件中。
解决方案
你应该知道的事情:
第 1 步 - 将您的视频转换为帧
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
-------------------------------------------------------------> step 2 - split
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
第 2 步 - 将帧拆分为 B、G、R
b,g,r = cv2.split(frame)
第 3 步 - 保存独立帧并转换为视频。