MATLAB实现图片栅格化

1.读取图片:首先,你需要使用imread函数读取要栅格化的图片。

2.设置栅格大小:确定你希望将图片划分成的栅格大小,即每个栅格的宽度和高度。

3.计算栅格数量:根据图片的总尺寸和栅格大小,计算出栅格的行数和列数。

4.遍历栅格:使用嵌套的for循环来遍历每一个栅格。

5.提取栅格内容:在每个栅格的位置上,使用矩阵索引提取出该栅格内的像素值。

6.处理栅格:对每个栅格进行所需的处理,比如二值化、灰度化等。

7.显示或保存结果:可以选择显示每个栅格的处理结果,或者将所有栅格的处理结果组合起来显示整幅栅格化后的图片,也可以保存处理后的图片。



clc;close all;clear all;warning off;%清除变量
rand('seed', 100);
randn('seed', 100);
format long g;


% (1) 读取图像
img0 = imread('1.png'); % 替换为你的图像路径
% (1) 读取图片
figure;
imshow(img0); % 显示原始图像
% 转换为灰度图像
img = double(rgb2gray(img0))/255;
size(img)

% (2) 对图片进行栅格化
grid_size = [20,20]; % 设置栅格大小,例如50x50像素
aaa = size(img) ./ grid_size;
grid_rows=aaa(1);
grid_cols=aaa(2);
grid_rows = floor(grid_rows);
grid_cols = floor(grid_cols);

rasterized_img = zeros(grid_rows*grid_size(1), grid_cols*grid_size(2));

G=zeros(grid_rows,grid_cols);% 栅格结果

for i = 1:grid_rows
    for j = 1:grid_cols
        % 提取栅格区域
        row_start = (i-1)*grid_size(1) + 1;
        row_end = i*grid_size(1);
        col_start = (j-1)*grid_size(2) + 1;
        col_end = j*grid_size(2);
        
        % 截取栅格图像
        grid_img = img(row_start:row_end, col_start:col_end);
        
        % 将栅格图像放入栅格化图像中
        rasterized_img(row_start:row_end, col_start:col_end) = grid_img;
        
        
        % 对栅格图像进行二值化
        %         mean(mean((grid_img)))
        if mean(mean((grid_img)))<0.95; % 计算阈值
            G(i,j)=0;
        else
            G(i,j)=1;
        end
    end
end


% G
figure;
imshow(G);
title('栅格化后');


G=flipud(G);%垂直翻转
bockmat=G;


grid_rows=aaa(1);
grid_cols=aaa(2);

% 设定网格参数
nx=grid_cols;% 划分数
ny=grid_rows;% 划分数

dx=grid_size(2);
dy=grid_size(1);
xmin=0;
xmax=nx*dx;
ymin=0;
ymax=ny*dy;

tic;
[nodetable,XY,nodenumber]=nodetablefun(nx,ny,dx,dy);% 计算节点表格
disp('计算节点表格完成');
XY(:,1)=XY(:,1)+xmin;
XY(:,2)=XY(:,2)+ymin;

bocktable=bocktablefun_tan(nodetable,nx,ny,nodenumber,bockmat);
disp('计算bocktable完成');

nodeset= find(bocktable==1);
title201='栅格模型';
drawshelf(XY,dx,dy,nodeset,title201);% 绘图

MATLAB实现图片栅格化-LMLPHP

MATLAB实现图片栅格化-LMLPHP

04-18 10:46