MATLAB裁剪視頻(裁剪固定區域)

最近因爲surface的處理性能不夠,1920X1080的視頻處理起來內存不夠,無奈只好做視頻裁剪,同時也是減少了無用信息的處理。

  • 需要輸入的是視頻的絕對路徑和視頻名。
  • 需要在顯示的第一幀圖像中標選想要裁剪的框
  • 需要給出輸出視頻的路徑

代碼如下:

dataDir = 'C:\Users\fskbo\Desktop\代碼\data';
%第一步:檢測參考幀
% Create a cascade detector object.
addpath(genpath('.'));
 
infilename='WIN_20200212_15_34_20_Pro.mp4'
% Read a video frame and run the detector. 
vidFile = fullfile(dataDir, infilename);
outfilename = [infilename(1:end-4),'_1st.avi'];%輸出文件名字
outName = fullfile('C:\Users\fskbo\Desktop\代碼\data',outfilename);
vid = VideoReader(vidFile);
frame = read(vid,1);
imshow(frame);
h = imrect;
loc = getPosition(h); %獲取手動標選框的座標
delete(h);
fr = round(vid.FrameRate);
len = vid.NumberOfFrames;
%%輸出文件創建
vidOut = VideoWriter(outName);
vidOut.FrameRate = 20;
open(vidOut)
videoFileReader = vision.VideoFileReader(vidFile);
videoFrame = step(videoFileReader);
imshow(videoFrame);
%drawnow
%標記選擇區域,bbox四個參數分別對應剪裁後左上角像素在原圖像位置,剪裁後圖像寬和高
bbox=[loc(1) loc(2) loc(3) loc(4)];
boxInserter = vision.ShapeInserter ( 'BorderColor','Custom',...
 'CustomBorderColor',[255 0 0],'LineWidth',3);
videoOut_chest = step(boxInserter, videoFrame,bbox);
%videoOut_chest = step(boxInserter, videoOut_chest,bbox_right);
figure(1),imshow(videoOut_chest,'border','tight');title('Detected image');
%%第一幀圖像裁剪
faceImage = imcrop(videoFrame,bbox);
% ? ?axes(handles.axes4);
imshow(faceImage);
drawnow
writeVideo(vidOut,im2uint8(faceImage));
h=waitbar(0,'開始檢測...','Name','正在跟蹤...');
%第二步:裁剪其他幀
n=1;
% Track the bbox over successive video frames until the video is finished.
while ~isDone(videoFileReader)
n=n+1;
% Extract the next video frame
 videoFrame = step(videoFileReader);
 % Insert a bounding box around the object being tracked
 % videoOut = step(boxInserter, videoFrame, bbox);
 faceImage = imcrop(videoFrame,bbox);
% Display the annotated video frame using the video player object
 % step(videoPlayer, faceImage);
 writeVideo(vidOut,im2uint8(faceImage));
h=waitbar(0.05+n*(0.85/len),h,[num2str(floor(100*(0.05+n*(0.85/len)))),'%']);
end
% Release resources
close(vidOut);
h=waitbar(0.9,h,[num2str(90),'%']);
release(videoFileReader);
h=waitbar(1,h,[num2str(1),'%']);
clear vid;
close(h)
%axes(handles.axes3);
cla
%axes(handles.axes4);
  cla
drawnow
發佈了217 篇原創文章 · 獲贊 622 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章