I have the x and y coordinates of a gray scale image. How to get the gray values for that particular set of coordinates?
2 次查看(过去 30 天)
显示 更早的评论
gray = rgb2gray(I5);
imtool(gray)
graydata = 0;
graydata = gray(sub2ind(size(gray)),(y(:)),(x(:)));
I tried this code.
Error in fourierdescriptorscode (line 18)
graydata = gray(sub2ind(size(gray)),round(y(:)),round(x(:))); - Command window displayed this.
Please answer as soon as possible. Thank you.
0 个评论
采纳的回答
Stephen23
2015-5-1
编辑:Stephen23
2015-5-1
You are putting way too many superfluous parentheses in there, and this is causing the error. If you just stick to putting in the parentheses that are actually required, then the code becomes easier to read and the problem is easier to identify. So instead of (x(:)) you should just put x(:), etc., which makes it much easier to keep track of the matching parentheses.
Then you would discover that the function parentheses for sub2ind are closed just after size(gray), and do not include the x and y values at all, as they should.
To make your code clearer and reduce the chance of writing this kind of basic bug, consider allocating the indices first. Then you would have something like this:
idx = sub2ind(size(gray),y(:),x(:));
graydata = gray(idx);
which makes it easier to debug because you can also check the values in idx.
2 个评论
Stephen23
2015-5-1
Which values? In what variable? What data are you using? How are you checking these values? What is the whole code?
You only give us part of the code and none of the data... Sorry, but reading minds is very difficult.
更多回答(1 个)
Image Analyst
2015-5-1
编辑:Image Analyst
2015-5-1
gray() is a built in function. Don't use that name.
Also, you can simply just use a for loop to get the values. No need for linear indexing and sub2ind(). I think the for loop is more intuitive and it's very fast for a small number of coordinates.
xr = round(x);
yr = round(y);
for k = 1 : length(x)
pixelValues(k) = grayImage(yr(k), xr(k));
end
2 个评论
Image Analyst
2015-5-5
Arrays are always (row, column), never (x, y). Images are just arrays, so you need to use row, column, which is y,x:
pixelValues(k) = grayImage(yr(k), xr(k));
like I showed you. Be careful about this. The x,y/row,column mixup is extremely common amongst MATLAB programmers.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Filter Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!