You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
How to caculate x,y coordinates in a contoured region
1 view (last 30 days)
Show older comments
Hello All
Hope yopu are all good. i have a question i used the code below. i contoured the region by imfreehand tool. i want to calculate the coordinates( x, y,z) in this region which i contourd. i can calculate the coordinates on the line which is made by imfreehand by ginput. but i need the coordinates which are in the contoured region.
% Display a file
I = imread('cat.jpg');
imshow(I);
zoom on; % use mouse button to zoom in or out
% Press Enter to get out of the zoom mode. % CurrentCharacter contains the most recent key which was pressed after opening % the figure, wait for the most recent key to become the return/enter key
waitfor(gcf,'CurrentCharacter',13) zoom reset zoom off imfreehand
% the figure, wait for the most recent key to become the return/enter key
imfreehand(gca,'closed',0) end
Any help is appreciated in advance.
Accepted Answer
Image Analyst
on 6 Sep 2013
Explain why you think you need the (x,y) coordinates of all the pixels inside the hand drawn region, rather than just the boundary coordinates. I've never needed them and suspect you don't really need them either. I know how to get them, but I don't want to send you down an unproductive path for no reason.
16 Comments
Muhammad
on 6 Sep 2013
Edited: Muhammad
on 6 Sep 2013
actually i want to compare (x,y,z) coordinates of 2 files one is image file and other is dose file. i need (x,y,z) values of every voxel inside that hand drawn region. one thing more working my mind that. if we devide that region into 5x5 (rowsxcolums) then we have 25 intersection points having (x,y,z) values. i want to put them into table.
Image Analyst
on 6 Sep 2013
imfreehand() works on a 2D image, so what are your "z" coordinates?
To get all the x,y coordinates in a masked image, use
[rows, columns] = find(maskedImage ~= 0);
Muhammad
on 6 Sep 2013
my image is CT image but i converted that to jpg. then how will i get z coordinate too? will it be thickness of the image? How do i mask please? here is my code
I = imread('cat.jpg');
imshow(I);
zoom on; % use mouse button to zoom in or out % Press Enter to get out of the zoom mode.
% CurrentCharacter contains the most recent key which was pressed after opening % the figure, wait for the most recent key to become the return/enter key waitfor(gcf,'CurrentCharacter',13) zoom reset zoom off imfreehand % the figure, wait for the most recent key to become the return/enter key imfreehand(gca,'closed',0) end
Image Analyst
on 6 Sep 2013
Are they medical images? If so, what do your legal folks say about the liability of converting medical images to jpeg? Anyway, here's my masking demo:
% Demo to have the user freehand draw an irregular shape over a gray scale image.
% Then it creates new images:
% (1) where the drawn region is all white inside the region and untouched outside the region,
% (2) where the drawn region is all black inside the region and untouched outside the region,
% (3) where the drawn region is untouched inside the region and all black outside the region.
% It also (4) calculates the mean intensity value and standard deviation of the image within that shape,
% (5) calculates the perimeter, centroid, and center of mass (weighted centroid), and
% (6) crops the drawn region to a new, smaller separate image.
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 16;
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'cameraman.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
imshow(grayImage, []);
axis on;
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
message = sprintf('Left click and hold to begin drawing.\nSimply lift the mouse button to finish');
uiwait(msgbox(message));
hFH = imfreehand();
% Create a binary image ("mask") from the ROI object.
binaryImage = hFH.createMask();
xy = hFH.getPosition;
% Now make it smaller so we can show more images.
subplot(2, 3, 1);
imshow(grayImage, []);
axis on;
drawnow;
title('Original Grayscale Image', 'FontSize', fontSize);
% Display the freehand mask.
subplot(2, 3, 2);
imshow(binaryImage);
axis on;
title('Binary mask of the region', 'FontSize', fontSize);
% Label the binary image and computer the centroid and center of mass.
labeledImage = bwlabel(binaryImage);
measurements = regionprops(binaryImage, grayImage, ...
'area', 'Centroid', 'WeightedCentroid', 'Perimeter');
area = measurements.Area
centroid = measurements.Centroid
centerOfMass = measurements.WeightedCentroid
perimeter = measurements.Perimeter
% Calculate the area, in pixels, that they drew.
numberOfPixels1 = sum(binaryImage(:))
% Another way to calculate it that takes fractional pixels into account.
numberOfPixels2 = bwarea(binaryImage)
% Get coordinates of the boundary of the freehand drawn region.
structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.
subplot(2, 3, 1); % Plot over original image.
hold on; % Don't blow away the image.
plot(x, y, 'LineWidth', 2);
drawnow; % Force it to draw immediately.
% Burn line into image by setting it to 255 wherever the mask is true.
burnedImage = grayImage;
burnedImage(binaryImage) = 255;
% Display the image with the mask "burned in."
subplot(2, 3, 3);
imshow(burnedImage);
axis on;
caption = sprintf('New image with\nmask burned into image');
title(caption, 'FontSize', fontSize);
% Mask the image and display it.
% Will keep only the part of the image that's inside the mask, zero outside mask.
blackMaskedImage = grayImage;
blackMaskedImage(~binaryImage) = 0;
subplot(2, 3, 4);
imshow(blackMaskedImage);
axis on;
title('Masked Outside Region', 'FontSize', fontSize);
% Calculate the mean
meanGL = mean(blackMaskedImage(binaryImage));
sdGL = std(double(blackMaskedImage(binaryImage)));
% Put up crosses at the centriod and center of mass
hold on;
plot(centroid(1), centroid(2), 'r+', 'MarkerSize', 30, 'LineWidth', 2);
plot(centerOfMass(1), centerOfMass(2), 'g+', 'MarkerSize', 20, 'LineWidth', 2);
% Now do the same but blacken inside the region.
insideMasked = grayImage;
insideMasked(binaryImage) = 0;
subplot(2, 3, 5);
imshow(insideMasked);
axis on;
title('Masked Inside Region', 'FontSize', fontSize);
% Now crop the image.
leftColumn = min(x);
rightColumn = max(x);
topLine = min(y);
bottomLine = max(y);
width = rightColumn - leftColumn + 1;
height = bottomLine - topLine + 1;
croppedImage = imcrop(blackMaskedImage, [leftColumn, topLine, width, height]);
% Display cropped image.
subplot(2, 3, 6);
imshow(croppedImage);
axis on;
title('Cropped Image', 'FontSize', fontSize);
% Put up crosses at the centriod and center of mass
hold on;
plot(centroid(1)-leftColumn, centroid(2)-topLine, 'r+', 'MarkerSize', 30, 'LineWidth', 2);
plot(centerOfMass(1)-leftColumn, centerOfMass(2)-topLine, 'g+', 'MarkerSize', 20, 'LineWidth', 2);
% Report results.
message = sprintf('Mean value within drawn area = %.3f\nStandard deviation within drawn area = %.3f\nNumber of pixels = %d\nArea in pixels = %.2f\nperimeter = %.2f\nCentroid at (x,y) = (%.1f, %.1f)\nCenter of Mass at (x,y) = (%.1f, %.1f)\nRed crosshairs at centroid.\nGreen crosshairs at center of mass.', ...
meanGL, sdGL, numberOfPixels1, numberOfPixels2, perimeter, ...
centroid(1), centroid(2), centerOfMass(1), centerOfMass(2));
msgbox(message);
Muhammad
on 6 Sep 2013
i think i need to explain my question more. in hand free region suppose we make 2 rows and 2 columns. and we have 4 intersection points there. i need (x and y) values of those intersection points.
Image Analyst
on 7 Sep 2013
What is a hand free region? Do you mean that you used imfreehand() to somehow super accurately trace out two columns and two rows in an image with perfectly straight sides so that they cross and form a cross or "+" shape? If you know the two rows and know the 2 columns, it's really easy and obvious what the four intersection pixels are. It's just (row1, col1), (row1, col2), (row2, col1), and (row2, col2).
Muhammad
on 7 Sep 2013
Dear Sir. suppose we have a scale not a image. scale must contains rows and columns. if we select some part of scale by imfreehand and that part must contains rows and columns intersections, that may be in any number depend on the shape we contoured.can we calculate that intersection points? if yes then how can we apply that on image? and how we calculate the (x,y) coordinate at that intersection.As sir every image is a matrix and has rows and columns. i think know question is more clear to answer.
Image Analyst
on 7 Sep 2013
I don't know what you mean by intersections of rows and columns. When you draw a freehand region you can have some arbitrarily-shaped amorphous blob. It has a bunch of pixels inside it, and each pixel has a (row, column) or (y, x) coordinate. I already told you how to use find() to find all of those rows and columns:
[rows, columns] = find(maskedImage ~= 0);
Since that is evidently not what you want, I have no idea what you want now. Please give an example with a small 10 by 10 matrix of numbers and tell me what you want the output to be. Or else post a screenshot.
Muhammad
on 9 Sep 2013
Bundle of thanks Dear Respecetd Sir. i got my all points here. again thank you so much.
Muhammad
on 10 Sep 2013
can we find these row and columns values in single excel sheet in work space? because now i find these in differnt sheets?
Muhammad
on 11 Sep 2013
yes in spread sheet but 2 different spread sheets, one for columns and one for rows.
Image Analyst
on 11 Sep 2013
Edited: Image Analyst
on 11 Sep 2013
Well, you don't need to find them in the worksheet, xlsread() will do that for you. Just use xlsread() and you'll get them, no matter where you put them, because xlsread will find them for you. You may need to specify the two sheetnames one at a time though in two separate calls to xlsread. You at least know what the worksheets are named - if you don't then open it up in Excel and look at the worksheet tabs.
Muhammad
on 16 Sep 2013
Dear Respected Dr., i tried but i did not understand. now i am reached at this point.when i contour some part of image then i cannot find the coordinates [Y,X]on the workspace. i cant find any thing on the workspace.my code is given below for creat excel sheet. i want that when i press Excelpushbutton then allthe [Y,X] values will come on the excel sheet or spreadsheet. also what will be the unit of these [Y,X] coordinates?is thes mm or cm? i have thickness between the slice is 0.18mm,which is my z coordinate. am i right?
if true
function ExcelPushbutton_Callback(hObject, eventdata, handles)
imshow(handles.maskedImage)
[Y, X] = find(handles.maskedImage ~= 0);
data=[Y,X];
end
hoping for early response. Isa
Image Analyst
on 16 Sep 2013
Not sure what you want to do. I'm not sure what "will come on the excel sheet" means. Instead of "come on" do you mean "come from" or "go to"? Call xlsread() if you want to retrieve values from a workbook. Call xlswrite() if you want to send values to a workbook.
Muhammad
on 16 Sep 2013
Edited: Muhammad
on 16 Sep 2013
when i applies the below code on a image like cat image then i can find [Y,X] coodinates on spread sheet with name of data that contains 2 arrays having Y and X values. X and Y seprately also available as a spread sheet in workspace. these values are the coordinates of each pixel inside the contoured region. but when i made interface then i cant find that spread shee on work space.
if true
I = imread('cat.jpg');
imshow(I);
% image;
zoom on; % use mouse button to zoom in or out
% Press Enter to get out of the zoom mode.
% CurrentCharacter contains the most recent key which was pressed after opening
% the figure, wait for the most recent key to become the return/enter key
waitfor(gcf,'CurrentCharacter',13)
zoom reset
zoom off
% imfreehand
% the figure, wait for the most recent key to become the return/enter key
h=imfreehand(gca,'closed',0);
pos = getPosition(h);
sz = size(I);
maskedImage = poly2mask(pos(:,1), pos(:,2), sz(1), sz(2));
[Y, X] = find(maskedImage ~= 0);
data=[Y,X];
end
Now i think you will better understand. thnaks in advance.
More Answers (0)
See Also
Categories
Find more on 3-D Volumetric Image Processing in Help Center and File Exchange
Tags
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)