使用遮罩从Matlab裁剪图片中的圆形图像

时间:2020-10-01 15:19:51

标签: image matlab

clear all, close all, clc; 

Img_filename=ls('C:\Users\User\Desktop\294.jpg');
I = imread('294.jpg');
imageSize = size(I);
%initial values: c_row=400, col_min=1, col_max=800, row_max=800, row_min= 1, radius = 400, c_col= 400
c_row= 40;                 %center of circle row value. DON'T CHANGE
radius= 40;                %radius of circle
StepSizeRow= 10;
StepSizeCol= 50;
%%
c_col=50;                  %center of circle column value. CHANGE BY 120
col_min= c_col-radius+1;    %column val left side of bounding box. CHANGE BY 120
col_max= c_col+radius;      %column val right side of bounding box. CHANGE BY 120

[rows, cols, rgb]= size(I); 
count = 0;
for j =  c_col:StepSizeCol: cols-radius
    row_min=c_row-radius+1;                  %row val top of bounding box. DON'T CHANGE
    row_max=c_row+radius;                    %row val bottom of bounding box. DON'T CHANGE
    for i= c_row:StepSizeRow:rows-radius
        ci = [i, j, radius];                 % center and radius of circle ([c_row, c_col, r]) og size (1920, 2560)
        [xx,yy] = ndgrid((1:imageSize(1))-ci(1),(1:imageSize(2))-ci(2));
        mask = uint8((xx.^2 + yy.^2)<ci(3)^2);
        croppedImage = uint8(zeros(size(I)));
        croppedImage(:,:,1) = I(:,:,1).*uint8(mask);
        croppedImage(:,:,2) = I(:,:,2).*uint8(mask);
        croppedImage(:,:,3) = I(:,:,3).*uint8(mask);
        sp(1) = col_min;                    %min(floor(p(1)), floor(p(2))); %xmin
        sp(2) = row_min;                    %min(floor(p(3)), floor(p(4))); %ymin
        sp(3) = col_max;                    %max(ceil(p(1)), ceil(p(2)));   %xmax
        sp(4) = row_max;                    %max(ceil(p(3)), ceil(p(4)));   %ymax
        row_min=row_min+StepSizeRow;
        row_max=row_max+StepSizeRow;
        % Index into the original image to create the new image
        MM = croppedImage(sp(2):sp(4), sp(1): sp(3),:);
        %Display the subsetted image with appropriate axis ratio
        count = count+1;
%         figure;
%         imshow(croppedImage)
%         figure; image(MM); axis image;
        FileName = fullfile('C:\Users\User\Desktop\Tensorflow\1cm 45deg circle cropped',sprintf('Cropped_Parallel_5x_20_400Radius_%d.jpg',count));
        imwrite(MM, FileName)

    end
    col_min=col_min+StepSizeCol;
    col_max= col_max+StepSizeCol;
end

我在这里使用的代码非常适合从“ 294.jpg”图像中裁剪圆形图像

裁剪顺序是从左上到左下,然后从上到下依次到第二列,然后到第三列,依此类推。

如何更改裁剪顺序,从左上角到右上角,然后从左向右移动第二个“行”,然后从左向右移动到第三个“行”?

0 个答案:

没有答案