Finding pixel location of centroid in a region - matlab

I have an image in Matlab where I am finding the all the centroids in it. There are multiple centroids in the image and I am using 'imellipse' to seclude one of them. I am trying to find the pixel location of one of centroids. Having the location pop-up in the command window of Matlab will be good enough.
Here is my code:
% --- Executes on button press in pushbutton15.
function pushbutton15_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton15 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
A = imread('PET_MRI_Brain_Tumor.jpg');
Z = imshow(A)
Ibw = im2bw(A);
Ibw = imfill(Ibw,'holes');
Ilabel = bwlabel(Ibw);
stat = regionprops(Ilabel,'centroid');
imshow(Z); hold on;
for x = 1: numel(stat)
plot(stat(x).Centroid(1),stat(x).Centroid(2),'bx');
end
e = imellipse(gca,[55 10 120 120])
BW = createMask(e,Z)
Here is the picture where I am trying to extrapolate the pixel location of the centroid marker.
http://imgur.com/DnSQTUi

Related

I would like to record time in seconds each time i am crossing a particular region in Matlab Guide

I would like to track the cursor position within the axes and adds a marker like this for instance(.).
Furthermore, I would like to record and display how much time was spent within a particular region (rectangle, indicating green each time the cursor is within the rectangle.)?
All this done in Guide .
The output in the fig is very different to what I was expecting.
See pictures.
1)The first picture is what I was expecting
2)The second pictures is what I have.
% --- Executes on mouse motion over figure - except title and menu.
function finger_WindowButtonMotionFcn(hObject,~, handles)
% hObject handle to finger (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
pos = get(hObject, 'currentpoint'); % get mouse location on figure
global x;
global y;
x = pos(1);
y = pos(2); % assign locations to x and y
set(handles.xloc, 'string', ['x loc:' num2str(x)]); % update text for x loc
set(handles.yloc, 'string', ['y loc:' num2str(y)]); % update text for y loc
% Determine if mouse is within the region
p_x = get(handles.region1,'XData');
p_x = p_x([1 2]);
p_y = get(handles.region1,'YData');
p_y = p_y([1 3]);
ax_xl = get(handles.axes1,'XLim');
ax_yl = get(handles.axes1,'YLim');
ax_units = get(handles.axes1,'Units');
if ~strcmp(ax_units,'pixels')
set(handles.axes1,'Units','pixels')
end
ax_pos = get(handles.axes1,'Position'); % axes1 position in pixels
if ~strcmp(ax_units,'pixels')
set(handles.axes1,'Units',ax_units);
end
% convert the patch XData and YData from axes coordinates to figure coordinates in pixels
p_x = (p_x-ax_xl(1))/(ax_xl(2)-ax_xl(1))*ax_pos(3)+ax_pos(1);
p_y = (p_y-ax_yl(1))/(ax_yl(2)-ax_yl(1))*ax_pos(4)+ax_pos(2);
persistent timein;
if isempty(timein)
timein = datetime('now');
end
if x >= p_x(1) && x <= p_x(2) && y >= p_y(1) && y <= p_y(2)
timein = datetime('now');
set(handles.region1,'FaceColor','g');
%writeline(handles.arduinoObj, "4&MOTOR_1_2_3_4&0!");
else
timeInPatch = seconds(datetime('now')-timein);
ax = ancestor(handles.region1, 'axes');
cp = ax.CurrentPoint;
text(ax, 0.52, cp(1,2), sprintf('%.3f sec.', timeInPatch), ...
'HorizontalAlignment','Left', ...
'VerticalAlignment','bottom', ...
'FontSize', 12, ...
'FontWeight', 'bold', ...
'Color', 'b')
set(handles.region1,'FaceColor','r');
%writeline(handles.arduinoObj, "0&MOTOR_1_2_3_4&0!");
end

Matlab GUI not showing line plot graph data

I'm working with my Matlab GUI file to play video and plot the mean value from the color channel (RGB). It has 2 axes, the first one for the video player and second axis for the mean graph, but the second axis is not showing any data, it just updates the x and y coordinate but not showing anything.
I've tried to change the handles, changes the next plot setting in the property inspector but it doesn't work
function main_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
video = vision.VideoFileReader();
handles.video = video;
frameCount = 0;
handles.frameCount = frameCount;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes main wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = main_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
handles.output = hObject;
varargout{1} = handles.output;
% --- Executes on button press in Browse.
function Browse_Callback(hObject, eventdata, handles)
% hObject handle to Browse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[ video_file_name,video_file_path ] = uigetfile({'*.avi'},'Pick a video file'); %;*.png;*.yuv;*.bmp;*.tif'},'Pick a file');
if(video_file_path == 0)
return;
end
input_video_file = [video_file_path,video_file_name];
fullpath = strcat(video_file_path,video_file_name);
set(handles.edit1,'String',fullpath);
video = vision.VideoFileReader(input_video_file);
vidFrame = step(video);
axes(handles.axes1);set(handles.StartButton,'String','Start');
frameCount = 1;
imshow(vidFrame);
drawnow;
axis(handles.axes1,'off');
for nChannel = 1:3
colorChannel = vidFrame(:,:,nChannel);
rawColorSignal(nChannel,frameCount) = mean(mean(colorChannel));
end
%plot(frameCount,rawColorSignal(1, :),frameCount,rawColorSignal(2, :),frameCount,rawColorSignal(3, :), handles.axes2);
axes(handles.axes2)
plot(frameCount,rawColorSignal(1, :));
grid on
drawnow;
axes(handles.axes1)
% Display Frame Number
%Update handles
handles.video = video;
guidata(hObject,handles);
% --- Executes on button press in StartButton.
function StartButton_Callback(hObject, eventdata, handles)
% hObject handle to StartButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if strcmp(get(handles.StartButton,'String'),'Pause')
set(handles.StartButton,'String','Start');
else
set(handles.StartButton,'String','Pause');
end
video = handles.video;
if isDone(video)
reset(video)
frameCount = 0;
handles.frameCount = frameCount;
end
frameCount = handles.frameCount;
while ~isDone(video) && strcmp(get(handles.StartButton,'String'),'Pause')
vidFrame = step(video);
imshow(vidFrame,'Parent',handles.axes1); %plot frame is specific axis
drawnow;
frameCount = frameCount + 1;
for nChannel = 1:3
colorChannel = vidFrame(:,:,nChannel);
rawColorSignal(nChannel,frameCount) = mean(mean(colorChannel));
end
plot(frameCount,rawColorSignal(1, :),'Parent',handles.axes2);
grid on
drawnow;
end
%plot(frameCount,rawColorSignal(1, :),'r',frameCount,rawColorSignal(2, :),'g',frameCount,rawColorSignal(3, :),'b','Parent', handles.axes2);
%drawnow;
set(handles.StartButton,'String','Start');
% --- Executes on button press in PauseButton.
function PauseButton_Callback(hObject, eventdata, handles)
% hObject handle to PauseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%axes(handles.axes2)
%surf(membrane(3))
What I expected is the line plot is visible and updating alongside the axes.
I think I found the problem:
Replace: plot(frameCount,rawColorSignal(1, :));
With: plot(1:frameCount,rawColorSignal(1, :));
Replace: plot(frameCount,rawColorSignal(1, :),'Parent',handles.axes2);
With: plot(1:frameCount,rawColorSignal(1, :),'Parent',handles.axes2);
plot(frameCount,... uses the scalar frameCount as X coordinates.
You want the X coordinates in your plot to be a vector that goes from 1 to frameCount.
In case you are getting an error, try:
plot(1:length(rawColorSignal(1, :)), rawColorSignal(1, :), 'Parent', handles.axes2);
I created the following sample code for demonstrating the problem:
Following sample is not plotting:
frameCount = 0;
rawColorSignal = [];
for i = 1:10
frameCount = frameCount + 1;
rawColorSignal(frameCount) = i;
end
plot(frameCount, rawColorSignal);
grid on
drawnow;
When replacing plot(frameCount, rawColorSignal); with plot(1:frameCount, rawColorSignal); it does:
frameCount = 0;
rawColorSignal = [];
for i = 1:10
frameCount = frameCount + 1;
rawColorSignal(frameCount) = i;
end
plot(1:frameCount, rawColorSignal);
grid on
drawnow;

Reading an audio file through Matlab GUI

I want to make a GUI in matlab that has 2 buttons. 1 Button (pushbutton1) loads the selected file and the second button (pushbutton2) executes a code.
This is what i have so far
% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, ventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename pathname] = uigetfile({'*.wav'}, 'Select File');
fullpathname = strcat (pathname, filename);
audio = wavread(fullpathname);
% --- Executes on button press in pushbutton2.function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% get a section of vowel
[x,fs]=wavread('audio',[24120 25930]);
ms20=fs/50; % minimum speech Fx at 50Hz
% plot waveform
t=(0:length(x)-1)/fs; % times of sampling instants
subplot(2,1,1);
plot(t,x);
legend('Waveform');
xlabel('Time (s)');
ylabel('Amplitude');
The mistake is in the following line
[x,fs]=wavread('audio',[24120 25930]);
How should I write it?
Also when plotting how do I make the plot appear on the GUI ?
wavread takes a filename as first argument. As audio is not a file in your current path (or maybe not the one you want), you cannot put this as first argument.
But the variable audio holds the signal itself, so you don't need to access to the file itself anylonger. Then, initialize fs at the same time:
[audio,fs] = wavread(fullpathname);
Then, if you need to pick up a part of your signal, just get a slice of it:
x = audio(24120 25930);
For plotting, add axes in your GUI and call plot with the handle of these axes as first parameters (doc of Matlab is full of examples of that :) ).
[data,fs] = wavread(filename);
x = data(24120:25930);
% to plot data
plot(handles.axes1,t,x);
%%assuming you didn't change the name of handle to axis
I tried your suggestions and I wrote it like this :
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename pathname] = uigetfile({'*.wav'}, 'Select File');
fullpathname = strcat (pathname, filename);
[data,fs] = wavread(filename);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%MODEL
% get a section of vowel
x = data(24120:25930);
ms20=fs/50; % minimum speech Fx at 50Hz
%
% plot waveform
t=(0:length(x)-1)/fs; % times of sampling instants
subplot(2,1,1);
plot(t,x);
legend('Waveform');
xlabel('Time (s)');
ylabel('Amplitude');
plot(handles.axes1,t,x);
%
% calculate autocorrelation
r=xcorr(x,ms20,'coeff');
%
% plot autocorrelation
d=(-ms20:ms20)/fs; % times of delays
subplot(2,1,2);
plot(d,r);
legend('Autocorrelation');
xlabel('Delay (s)');
ylabel('Correlation coeff.');
plot(handles.axes2,d,r);
ms2=fs/500 % maximum speech Fx at 500Hz
ms20=fs/50 % minimum speech Fx at 50Hz
% just look at region corresponding to positive delays
r=r(ms20+1:2*ms20+1)
[rmax,tx]=max(r(ms2:ms20))
fprintf('rmax=%g Fx=%gHz\n',rmax,fs/(ms2+tx-1));
But I get the following erros:
?? Undefined function or method 'data' for input arguments of type 'double'.
Error in ==> untitled>pushbutton2_Callback at 94
x = data(24120:25930);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> untitled at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==> #(hObject,eventdata)untitled('pushbutton2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
ur problem was in the variable ure giving for wavread to read, instead of [data,fs] = wavread(filename); use:[data,fs] = wavread(fullpathname). It worked for me.

Trying to do find the centroid of a section of an image in Matlab

I am trying to find a way to draw a box around a section of an image in Matlab and find the centroid of that image. I would ideally want the "new" section to show up next to my original image, then I can to the centroid of that "new" image.
Here is my code:
% --- Executes on button press in pushbutton15.
function pushbutton15_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton15 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
A = imread('PET_MRI_Brain_Tumor.jpg');
Z = imshow(A)
Ibw = im2bw(A);
Ibw = imfill(Ibw,'holes');
Ilabel = bwlabel(Ibw);
stat = regionprops(Ilabel,'centroid');
imshow(Z); hold on;
for x = 1: numel(stat)
plot(stat(x).Centroid(1),stat(x).Centroid(2),'bx');
end
e = imellipse(gca,[55 10 120 120])
BW = createMask(e,Z)
Here is the image that I am trying to put a mask over and find the centroid of that section.
Once you have a BW mask like this:
e = imellipse(gca,[55 10 120 120])
BW = createMask(e,Z)
or that has created with any other method (e.g. imfreehand or some type of segmentation algorithm), you can use 'regionprops':
s = regionprops(BW, 'Centroid');
If there is only one area/"region" in the BW image, the centroid is just:
s(1).Centroid

Imagesc ButtonDownFcn problems in MATLAB, using custom toolbar action

I'm trying to use the ButtonDownFcn on an imagesc figure in MATLAB. I want to enable this function by clicking on a custom button I have created on the toolbar.
The ButtonDownFcn will call methods that will cause it to return the position of the pixel selected using the ButtonDownFcn, so that I can graph how that pixel changes through time.
NOTES:
- I am using GUIDE in matlab
- imagesc is plotting a 3D matrix. I already have implemented code that allows me to travel through how the image changes through time, using a button created in GUIDE.
What I am struggling with, at the moment, is the ButtonDownFcn of the imagesc. I've read over and over on how to do this (through research on the internet), but I can't seem to get it to work.
Any help is appreciated.
Here is my code:
% --------------------------------------------------------------------
function ui_throughTime_ClickedCallback(hObject, eventdata, handles)
% hObject handle to ui_throughTime (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
valS = get(handles.txt_zaxis,'string');
display(valS);
val = str2num(valS);
d = handles.data;
m = imagesc(d(:,:,val),'parent',handles.axis, 'HitTest', 'off','buttondownfcn',{#getPlace, handles});
set(handles.axis,'buttondownfcn',{#getPlace, handles,m});
function getPlace(hObject,handles,event_obj,place)
% data = randn(120,160);
% ax = axes;
% imagesc(data,);
if (gcf == place)
pause(1);
cursor = get(handles.axis,'CurrentPoint'); % get point
% Get X and Y from point last clicked on the axes
x = (cursor(1,1));
y = (cursor(1,2));
disp(['x = ' num2str(x) ' y = ' num2str(y)]);
end
Here is a simple example:
%% Init
fig_h = figure('CloseRequestFcn', 'run = 0; delete(fig_h);');
rgb = imread('peppers.png');
run = 1; t = 0;
%% Loop
while run
t = t + 0.05;
imagesc(rgb*sin(t), 'ButtonDownFcn', 'disp(''Clicked'')');
pause(0.01);
end
Above the 'ButtonDownFcn' of the image is being used so the 'HitTest' property of the image must be 'On'.
Below is the case that the 'ButtonDownFcn' of the axes are used and since the image is in front of the axes, 'HitTest' property of the image should be 'Off' or the axes won't be selectable.
%% Loop
ax = axes;
while run
t = t + 0.05;
imagesc(rgb*sin(t), 'Parent', ax, 'HitTest', 'Off');
set(ax, 'ButtonDownFcn', 'disp(''Clicked'')')
pause(0.01);
end
It's also possible to use the figure 'ButtonDownFcn' and again the image 'HitTest' should be 'Off'. However in this case clicked points of outside of the image ( or interested area) should be filtered programmatically.
Hope it helps.