MATLAB实时图像裁剪:绘制动态矩形框并保存裁剪结果

本文将介绍如何在 MATLAB 中实现实时图像裁剪,允许用户在裁剪前通过绘制动态矩形框来选择裁剪区域。

问题描述

您想在裁剪图像之前实时显示一个 100x100 的矩形框,以便精确选择裁剪区域。

解决方案

我们可以使用 MATLAB 的图像处理工具箱中的以下函数来实现此功能:

  • rectangle: 在图像上绘制矩形框。* imshow: 显示图像。* ginput: 获取鼠标点击坐标。* imcrop: 裁剪图像。

代码示例matlabclcclear all

path = 'D:\桌面\陈家山煤矸\4000\矸-分开';path0 = strcat(path, '0');

files0 = dir(fullfile(path0));len0 = length(files0);

for i = 3:len0 a = imread(strcat(files0(3).folder, '', files0(i).name)); h = imshow(a); hold on

% 绘制初始的100x100矩形框    x_init = 1;    y_init = 1;    rect = rectangle('Position', [x_init, y_init, 100, 100], 'EdgeColor', 'r', 'LineWidth', 2);

for kk = 1:4        [x, y] = ginput(1);

    while true            % 更新矩形框的位置            set(rect, 'Position', [x(1), y(1), 100, 100]);

        % 更新图像显示            j = imcrop(a, [x(1), y(1), 100, 100]);            set(h, 'CData', j);            drawnow;

        [x_new, y_new, button] = ginput(1);

        if button == 1                % 如果鼠标左键点击,则继续下一次操作                break;            elseif button == 3                % 如果鼠标右键点击,则保存图像                imwrite(j, ['D:\桌面\陈家山煤矸\4000\9通道同时裁剪\0\gangue\', 'ganguec4', int2str(i - 3), '-', int2str(kk), '.JPG']);                for c = 1:8                    path1 = strcat(path, num2str(c));                    files1 = dir(fullfile(path1));                    a1 = imread(strcat(path1, '\', files1(i).name));                    cc = imcrop(a1, [x(1), y(1), 100, 100]);                    imwrite(cc, ['D:\桌面\陈家山煤矸\4000\9通道同时裁剪\', num2str(c), '\gangue\', 'ganguec4', int2str(i - 3), '-', int2str(kk), '.JPG']);                end

            % 按任意键继续下一次操作                pause;            end        end    end

closee

原文地址: https://www.cveoy.top/t/topic/Bj5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录