How do I circular crop using matlab?

32 views Asked by At

I am trying to circular crop the video that is recorded. I don't understand the ci command line and the gray_frame line.

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)
1

There are 1 answers

0
MH N On

Assuming that ci variable is a vector containing parameters for a circle,

Problems :

  1. The variables xx and yy are undefined.
  2. You are incorrectly attempting to directly crop gray_frame using a condition. MATLAB does not support this operation directly on the array without predefined xx and yy.

try this

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