How do you randomly choose a grey bar in picture to turn white?
조회 수: 1(최근 30일)
표시 이전 댓글
I have the task to randomly choose a bar to be the target in a stimulus experiment with grey bars. The code for the bars thus far is stated beneath. However, it turns none of the bars in white. In the end, I have to have two pictures: one with a black background and 16 grey bars and the other one with just one randomly chosen bar white.
Can somebody help me how to randomly choose one of the bars to become white?
picture=zeros(500,500);
picture(100,96:104)=100;
picture(200,96:104)=100;
picture(300,96:104)=100;
picture(400,96:104)=100;
picture(100,196:204)=100;
picture(200,196:204)=100;
picture(300,196:204)=100;
picture(400,196:204)=100;
picture(100,296:304)=100;
picture(200,296:304)=100;
picture(300,296:304)=100;
picture(400,296:304)=100;
picture(100,396:404)=100;
picture(200,396:404)=100;
picture(300,396:404)=100;
picture(400,396:404)=100;
% Saving as image
imwrite(picture,'stimulusimage.tiff','tiff')
% Replacing a random bar with colour white ????
x=picture==100;
y=length(x)==9; % =9 because I thought that when x has a length of 9 times 1 (1 1 1 1 1 1 1 1 1) that represents a grey bar
picture(y)=255;
% Saving as image
imwrite(picture,'stimulusimagewithwhitebar.tiff','tiff')
댓글 수: 0
채택된 답변
Adam Danz
2020년 1월 26일
편집: Adam Danz
2020년 1월 27일
For grayscale images, imwrite() assumes that the dynamic range of the first input is [0,1] and automatically scales the data by 255 before writing it to the file as 8-bit values.
gray = 100/255;
picture=zeros(500,500);
picture(100,96:104)=gray;
picture(200,96:104)=gray;
% etc....
To randomly select a bar in the image and change its color to white, you can use bwlabel (requires Image Processing Toolbox) to identify the bar-groups, then randomly select one and change its value to 1.
% Group the picture values
bwl = bwlabel(picture > 0);
% Select a random segment
randSection = randi(max(bwl(:)),1,1);
% Set that bar to white
picture(bwl==randSection) = 1;
% Show image
imshow(picture) % or, in your case, imwrite(...)
댓글 수: 0
추가 답변(2개)
Stijn Haenen
2020년 1월 26일
This is most likely not the best way to do it but it works:
picture=zeros(50,50);
picture(10,10:12)=100;
picture(20,10:12)=100;
picture(30,10:12)=100;
picture(40,10:12)=100;
picture(10,20:22)=100;
picture(20,20:22)=100;
picture(30,20:22)=100;
picture(40,20:22)=100;
picture(10,30:32)=100;
picture(20,30:32)=100;
picture(30,30:32)=100;
picture(40,30:32)=100;
picture(10,30:32)=100;
picture(20,30:32)=100;
picture(30,30:32)=100;
picture(40,30:32)=100;
% Saving as image
%imwrite(picture,'stimulusimage.tiff','tiff')
% Replacing a random bar with colour white ????
imagesc(picture)
[x,y]=find(picture==100);
x0=datasample(x,1);
y0=datasample(y,1);
picture(x0-3:x0+3,y0-3:y0+3)=picture(x0-3:x0+3,y0-3:y0+3)*2.5;
figure()
imagesc(picture)
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!