如何使用 matlab 进行圆形裁剪?

问题描述 投票:0回答:1

我正在尝试循环裁剪录制的视频。我不明白 ci 命令行和gray_frame 行。

clear all
close all
clc

v = VideoReader("SquareWaveWithPlasticBall_90SLPM_Ceramic_16Hz_2.5G_10FPS.mp4"); 
i = 0;

while hasFrame(v) 

        frame = readFrame(v); 
        %imtool(frame)
        %imhist(frame);
        gray_frame = rgb2gray(frame); 
        %imhist(gray_frame)
        binary_frame = imbinarize(gray_frame,0.3) ;

ci = [638, 484, 512.75];
gray_frame = grey_frame((xx.^2 + yy.^2)<ci(1)^2);


        file = sprintf("a_frame_%d",i); 
        myFolderpath = 'D:\MichaelJ\test4\BinarizedImages\';
        FILENAME = string(strcat(myFolderpath, file, '.png')); 
        imwrite(binary_frame, FILENAME);
        %imshow(G3)
        i = i + 1; 
        %imshow(binary_frame)


        %writeVideo(binary_frame, double(BW));
end 

clear reader
%close(writer)
matlab image-processing video
1个回答
0
投票

假设 ci 变量是一个包含圆参数的向量,

问题:

  1. 变量 xx 和 yy 未定义。
  2. 您错误地尝试使用条件直接裁剪gray_frame。 MATLAB 不支持直接在没有预定义 xx 和 yy 的数组上进行此操作。

试试这个

v = VideoReader("your video file");
frameCounter = 0;
ci = [x_center, y_center, radius]; % Circle parameters, put value instead
outputFolderPath = 'your destination folder path';

% Check if the output folder exists, if not, create it
if ~exist(outputFolderPath, 'dir')
    mkdir(outputFolderPath);
end

% Process each frame in the video
while hasFrame(v)
    frame = readFrame(v); 
    grayFrame = rgb2gray(frame);
    
    [x, y] = meshgrid(1:size(grayFrame, 2), 1:size(grayFrame, 1));
    distances = ((x - ci(1)).^2 + (y - ci(2)).^2);
    mask = distances <= ci(3)^2;

    croppedGrayFrame = grayFrame; % Apply the mask to the grayscale image
    croppedGrayFrame(~mask) = 0; % Pixels outside the circular mask are set to 0 (black)
    
    binaryFrame = imbinarize(croppedGrayFrame, 0.3);
    
    fileName = sprintf("a_frame_%d.png", frameCounter);
    fullPath = fullfile(outputFolderPath, fileName);
    
    imwrite(binaryFrame, fullPath);
    
    frameCounter = frameCounter + 1; 
end
© www.soinside.com 2019 - 2024. All rights reserved.