How to extract odd values and even values from a 500x500 black image ?

6 次查看(过去 30 天)
I want to extract the even and odd numbers from 500x500 black matrix to turn them white without using loops or conditions statement.
  3 个评论

请先登录,再进行评论。

回答(2 个)

Image Analyst
Image Analyst 2022-3-6
编辑:Image Analyst 2022-3-6
Do you have any other numbers other than 0? If so you can use rem(M, 2). Observe:
M = magic(5)
M = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
mCopy = M;
oddIndexes = rem(mCopy, 2) == 1
oddIndexes = 5×5 logical array
1 0 1 0 1 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 1 0 1 0 1
oddNumbers = M(oddIndexes) % Extract the odd numbers.
oddNumbers = 13×1
17 23 11 5 1 7 13 19 25 21
% Turn the odd numbers to white (255)
mCopy(oddIndexes) = 255
mCopy = 5×5
255 24 255 8 255 255 255 255 14 16 4 6 255 20 22 10 12 255 255 255 255 18 255 2 255
evenIndexes = rem(mCopy, 2) == 0
evenIndexes = 5×5 logical array
0 1 0 1 0 0 0 0 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 1 0
evenNumbers = M(evenIndexes)
evenNumbers = 12×1
4 10 24 6 12 18 8 14 20 2
% Turn the even numbers to white (255)
mCopy = M; % Reset mCopy so there are no 255's in there anymore.
mCopy(evenIndexes) = 255
mCopy = 5×5
17 255 1 255 15 23 5 7 255 255 255 255 13 255 255 255 255 19 21 3 11 255 25 255 9

DGM
DGM 2022-3-6
编辑:DGM 2022-3-6
Consider the matrix:
A = randi([10 99],5,5)
A = 5×5
37 23 33 22 34 58 58 16 79 86 11 39 73 93 97 11 37 92 79 19 32 19 47 48 85
% get elements from odd linear indices
oddelems = A(1:2:numel(A))
oddelems = 1×13
37 11 32 58 37 33 73 47 79 79 34 97 85
% get elements from even linear indices
evenelems = A(2:2:numel(A))
evenelems = 1×12
58 11 23 39 19 16 92 22 93 48 86 19
That's linear indices. Maybe you want to address odd or even rows/columns:
% get elements from odd rows
oddrows = A(1:2:size(A,1),:)
oddrows = 3×5
37 23 33 22 34 11 39 73 93 97 32 19 47 48 85
% get elements from even rows
evenrows = A(2:2:size(A,1),:)
evenrows = 2×5
58 58 16 79 86 11 37 92 79 19
... and so on for columns
EDIT: I'm dumb. I forgot you wanted to set pixels to white.
The above still holds. You're still trying to address your array. Just apply that to an assignment:
B = zeros(5)
B = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
B(1:2:numel(B)) = 1 % set odd linear indices to 1
B = 5×5
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
... and so on

Community Treasure Hunt

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

Start Hunting!

Translated by