我在我的 gui 中有一个添加了网格线的图像。我需要能够创建和保存一个文本文件,该文件具有 N x M 维度的图形,其中包含网格中每个框的内容。
有没有办法做到这一点?
我在我的 gui 中有一个添加了网格线的图像。我需要能够创建和保存一个文本文件,该文件具有 N x M 维度的图形,其中包含网格中每个框的内容。
有没有办法做到这一点?
这是一个例子。
这应该是主脚本。
Grid_Size = [5 5];
Grid_Type = 1; % The group of the new clicked points.
% Initialize
Grid_Matrix = zeros(Grid_Size);
grid_h = []; % Grid image handle
fig_h = figure('Units', 'Normalized');
% Show your image
rgb = imread('peppers.png');
im_h = imshow(rgb);
% Shut off the 'HitTest' to keep the functionality of figure ButtonDownFcn
set(im_h, 'HitTest', 'Off');
hold on % Hold on for the overlaying grid image.
% Image normalized position
Image_Pos = get(ancestor(im_h, 'axes'), 'Position');
im_size = size(rgb(:,:,1));
% Set the Mouse click callback for the figure (to a script in this case)
set(fig_h, 'ButtonDownFcn', 'Mouse_Click');
脚本回调,我建议脚本而不是函数,以避免范围等的复杂性。
Clicked = fliplr((get(fig_h, 'CurrentPoint') - Image_Pos(1:2))./Image_Pos(3:4));
if ~sum(Clicked < 0) && ~sum(Clicked > 1) % If inside of the image is clicked
% Find the corresponding matrix index
ind = num2cell(ceil(Clicked.*Grid_Size));
% and toggle that element
if Grid_Matrix(ind{:}) == 0
Grid_Matrix(ind{:}) = Grid_Type;
else
Grid_Matrix(ind{:}) = 0;
end
% Show the result to user
delete(grid_h); % delete the previous grid image
% resize the Grid Matrix to the image size
Grid_Matrix_rs = imresize(flipud(Grid_Matrix), im_size, 'box');
Grid_Matrix_rgb = label2rgb(Grid_Matrix_rs, 'spring', 'b');
grid_h = imshow(Grid_Matrix_rgb);
set(grid_h, 'HitTest', 'Off');
set(grid_h, 'AlphaData', 0.3); % Show the grid image with an opacity
% Write data to file after each update (user click)
dlmwrite('GridBox.dat', flipud(Grid_Matrix));
end
请注意,flipud
用于翻转矩阵以匹配图像索引。
在单击期间,您可以Grid_Type
(使用 UI 或在命令窗口中)更改为另一个整数,以便获得另一种颜色。但是以前的颜色可能会改变,但最后所有相同的颜色在Grid_Matrix
.
你会得到类似的东西:
对应于此Grid_Matrix
:
4,0,3,0,2
0,1,0,0,0
3,0,1,0,4
2,0,2,1,0
0,0,3,0,0
从文件中读取结果
res = dlmread('GridBox.dat')