How to Create Alternating Black Columns Across an Image?

I have an image X and I would like to create black columns going across the image that are 16 pixels thick with a distance of 16 pixels between each column and I have no idea how to do this. The best I could do was make one column using this line of code:
X(:,1:16,:) = 0;
Also I am not allowed to solve the problem using loops.

 Accepted Answer

Hello Richard! You can try this:
size_of_column = 16;
img = imread('image_exemple.jpg');
imshow(img);
mask = zeros(size(img));
for i=1:size(mask,2)
if(mod(round(i/size_of_column),2) == 1)
mask(:,i,:) = 1;
end
end
figure();
img_final(:,:,:) = uint8(double(img(:,:,:)).*mask(:,:,:));
imshow(img_final)
The result:

6 Comments

Hi Jose,
This is exactly the result I need however I am not allowed to use loops which is why I am very confused. Is there a way to do the same thing without the loop? Thank you for your help!
Also if it is of any help answering this will also allow me to solve my problem
https://www.mathworks.com/matlabcentral/answers/355894-replacing-values-of-a-larger-matrix-with-that-of-a-smaller-matrix
Hello Richard. I really prefer the first code with the for loop. But the code above works:
size_column = 16;
img = imread('img.jpg');
imshow(img);
imgSiz = [size(img,1),size(img,2)];
blkSiz = [size(img,1),size_column];
numRep = imgSiz./blkSiz;
basMat = toeplitz(mod(0:numRep(1)-1,2),mod(0:numRep(2)-1,2));
mask(:,:,1) = repelem(basMat,size(img,1),size_column);
aux_matrix = zeros(size(img,1),(size(img,2)-size(mask,2)));
mask = horzcat(mask,aux_matrix);
mask(:,:,2) = mask(:,:,1);
mask(:,:,3) = mask(:,:,1);
figure();
img_final(:,:,:) = uint8(double(img(:,:,:)).*mask(:,:,:));
imshow(img_final);
Thank you for your help this works as well!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!