我期待选择一个区域的图像在matlab中使用鼠标,返回角落的x/y给用户。
在线查看,图像处理工具箱中的getrect函数正是这样做的,但是我没有图像处理工具箱。
开放源码的替代方案是在matlab文件交换上吗?
标记
发布于 2014-05-29 20:06:58
如果您可以使用全局变量和回调,那么下面的可能就可以了。创建一个传递(例如)希望显示的图像的函数
function extractblock(I)
% clear all global variables (or just those specific to this app)
clear GLOBAL;
% display the image
figure;
image(I);
% set callbacks for the handling of the mouse button down, motion, and
% up events against this figure
set(gcf,'WindowButtonDownFcn', @myButtonDownCallback, ...
'WindowButtonUpFcn', @myButtonUpCallback, ...
'WindowButtonMotionFcn', @myButtonMotionCallback);
end现在定义回调。从鼠标按钮向下事件开始,该事件只记录鼠标按钮已被按下及其位置(此回调和其他回调都可以与上述函数放在同一个文件中):
function myButtonDownCallback(~,~)
global IS_BUTTON_DOWN;
global RECT_START_COORD;
IS_BUTTON_DOWN = true;
% get top left corner of rectangle
RECT_START_COORD = get(gca,'CurrentPoint');
end现在使用回调处理鼠标运动,当用户将鼠标指针移动到图像上时,回调将绘制(或重新绘制)矩形:
function myButtonMotionCallback(~,~)
global IS_BUTTON_DOWN;
global RECT_START_COORD;
global RECT_END_COORD;
global RECTANGLE_HANDLE;
if ~isempty(IS_BUTTON_DOWN) && IS_BUTTON_DOWN
% get bottom right corner of rectangle
RECT_END_COORD = get(gca,'CurrentPoint');
% get the top left corner and width and height of
% rectangle (note the absolute value forces it to "open"
% from left to right - need smarter logic for other direction)
x = RECT_START_COORD(1,1);
y = RECT_START_COORD(1,2);
w = abs(x-RECT_END_COORD(1,1));
h = abs(y-RECT_END_COORD(1,2));
% only draw the rectangle if the width and height are positive
if w>0 && h>0
% rectangle drawn in white (better colour needed for different
% images?)
if isempty(RECTANGLE_HANDLE)
% empty so rectangle not yet drawn
RECTANGLE_HANDLE = rectangle('Position',[x,y,w,h],'EdgeColor','w');
else
% need to redraw
set(RECTANGLE_HANDLE,'Position',[x,y,w,h],'EdgeColor','w');
end
end
end
end现在处理鼠标向上事件,该事件将从图形中移除矩形,并将矩形的角写出到命令窗口(如果需要返回值,则必须添加返回某种矩阵的方法):
function myButtonUpCallback(~,~)
global IS_BUTTON_DOWN;
global RECTANGLE_HANDLE;
global RECT_START_COORD;
global RECT_END_COORD;
% reset the button down flag
IS_BUTTON_DOWN = false;
% delete the rectangle from the figure
delete(RECTANGLE_HANDLE);
% clear the handle
RECTANGLE_HANDLE = [];
% compute the top left (tl) and bottom right (br) coordinates
tl = [RECT_START_COORD(1,1) RECT_START_COORD(1,2)];
br = [RECT_END_COORD(1,1) RECT_END_COORD(1,2)];
% compute the top right (tr) and bottom left (bl) coordinates
tr = [br(1) tl(2)];
bl = [tl(1) br(2)];
% write coordinates to command window
fprintf('(%f,%f)\t',tl(1),tl(2));
fprintf('(%f,%f)\n',tr(1),tr(2));
fprintf('(%f,%f)\t',bl(1),bl(2));
fprintf('(%f,%f)\n',br(1),br(2));
fprintf('\n');
% optionally display the block from the image
end以上是从图像中提取用户定义块的快速方法,缺少一些逻辑来处理从右到左绘制的矩形。希望这能有所帮助!
https://stackoverflow.com/questions/23939854
复制相似问题