How do i change specific values in a matrix/image
11 次查看(过去 30 天)
显示 更早的评论
I have a black image (a matrix full of zeros). I also have 3 1x181 arrays with data in, the first two arrays, x and y correspond to the coordinates at which within the image. I want to replace the value '0' at these specific coordinates with the third data set z, in other words change the intensity to z values are the coordinates x y. Can somebody please help me with the for loop, or else I will have to do it manually - for example K(x,y)=z for every data point where K is the black image or matrix with 0s.
0 个评论
回答(2 个)
Stephen23
2018-8-8
编辑:Stephen23
2018-8-8
im = ... 2D image.
idx = sub2ind(size(im),row,col);
im(idx) = z
If your image is a 3D array (i.e. an RGB image), then you will also need to provide the page dimension as appropriate, or repmat the index and z.
3 个评论
Stephen23
2018-8-8
编辑:Stephen23
2018-8-8
@Panagiota Chatzi: I did not mention loops anywhere in my answer, so it is not clear to me what your comment relates to. As I wrote in my answer, you can easily use sub2ind:
>> row = [ 64,180,297,416];
>> col = [ 1, 1, 2, 2];
>> z = [807,796,794,793];
>> im = zeros(500,2); % 2D image of zeros.
>> idx = sub2ind(size(im),row,col);
>> im(idx) = z;
And we can easily find which elements of the image im are non-zero:
>> [r,c] = find(im) % locations of non-zero elements.
r =
64
180
297
416
c =
1
1
2
2
>> im(64,1) % check if the first value is correct.
ans = 807
So sub2ind easily put the correct value into the expected location. I don't see why you need any loops.
Alex Fratila
2018-8-8
You don't need any loops. Stephen's answer is all that you would need, because the sub2ind function combines your x and y vectors so you don't need to iterate through them manually. Then, the last line assigns the values at the given indices to the values from z. So, with your data:
x=[64 180 297 416];
y=[1 1 2 2];
z=[807 796 794 793];
idx = sub2ind(size(image),x,y);
image(idx) = z;
However, I think part of the issue here is that it seems like you want to save this modified image. Right now, this doesn't modify the original image. If you want to do this, use the imwrite function:
imwrite(image, 'filename');
Alex Fratila
2018-8-8
Does this work:
for i = 1:181
image(x(i), y(i)) = z(i);
end
2 个评论
Alex Fratila
2018-8-8
In what way? Does it error, or does it not do what you intended?
Also, if you set a breakpoint after changing one pixel, then in the command window you print out the value at that pixel, is it still 0?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!