a = imread('lena512.bmp');
%image(a);
title('main img');
colormap(gray(256));
daspect([1 1 1]);
% now i want to take the half of the pixels from this img generated randomly and other half default(white,black doesnt matter ,and save it to other matrix like image2 with the same size.

5 Kommentare

Try this
mask = randi([0 1], size(a),'like',a);
maskedA = a.*mask;
image(maskedA)
Denis Rahim
Denis Rahim am 22 Okt. 2019
thx a lot <3
Adam Danz
Adam Danz am 22 Okt. 2019
Bearbeitet: Adam Danz am 22 Okt. 2019
[Edit]
This approach would work well with m-by-n grayscale images or files containing indexed images. Note that it doesn't necessarily choose half of the pixels.
To choose exactly half of the pixels,
randIdx = randsample(numel(A),floor(numel(A)/2));
image2 = a;
image2(randIdx) = 0;
For files containing truecolor images, the output will be an m-by-n-by-3 array in which case you'd need to make sure that each RGB value was being set to the same value (which is the approach in my answer).
Daniel M
Daniel M am 22 Okt. 2019
Thanks Adam, it was sloppy :P
Adam Danz
Adam Danz am 22 Okt. 2019
But it's a good solution if the image is 2D. Feel free to post that idea to the answers section.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Adam Danz
Adam Danz am 22 Okt. 2019
Bearbeitet: Adam Danz am 22 Okt. 2019

2 Stimmen

"i want to take the half of the pixels from this img generated randomly and other half default(white,black doesnt matter ,and save it to other matrix like image2 with the same size."
This assumes you're working with an RGB truecolor image that has 3 dimensions. It chooses half of your pixels randomly and assigns [0,0,0] to their RGB values.
a = imread('lena512.bmp');
imSize = numel(a)/size(a,3); % Number of elements per 'RGB' (3rd dimension)
randIdx = randsample(imSize,floor(imSize/2)); % Randomly choose half of the indices
randIdx = randIdx(:) + imSize.*(0:size(a,3)-1); % Duplicate the indices to represent each RGB element
image2 = a; % Duplicate image
image2(randIdx(:)) = 0; % Replace the RGB values at each randomly chosen position (use 255 for white)
image(image2) % Show updated image

Gefragt:

am 22 Okt. 2019

Kommentiert:

am 22 Okt. 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by