using threshold on 3D images to creat mask for training Unet
1 view (last 30 days)
Show older comments
I am using this code for 128x128x128 3D mirco CT image
% Open input and output files
fid3DOCT = fopen('SampleA_128x3_#1.raw','r');
fid3DOCTout = fopen('SampleA_128x3_#1_segmented.raw','w');
% Define image dimensions
nx = 128;
ny = 128;
nz = 128;
% Read input image
A = fread(fid3DOCT,nx*ny*nz, 'uint8');
A = uint8(reshape(A,nx,ny,nz));
%Define thresholds for segmentation
threshold1 = 48; % Threshold for class 1
threshold2 = 58; % Threshold for class 2
% You can adjust these thresholds as needed
% Apply segmentation
outputImage = zeros(size(A)); % Initialize segmented image
outputImage(A <= threshold1) = 1; % Class 1
outputImage(A > threshold1 & A <= threshold2) = 2; % Class 2
outputImage(A > threshold2) = 3; % Class 3
% Write segmented image to output file
for i = 1:nz
fwrite(fid3DOCTout, outputImage(:,:,i), 'uint8');
end
but what I get is a black image
I attached the image I am working on it is actually .raw but I saved as .png so I can attach it
Can you please see why the result is black
2 Comments
Walter Roberson
on 21 Apr 2024
You will get out a file that is uint8 1, 2 or 3. That is going to look black unless you use imagesc()
Answers (1)
Thomas
on 21 Apr 2024
Your segmentation routine is correct. However, the issue is that the visualization of a uint8 or double composed of index values of [1, 2, 3] will 'appear' black without scaling. For example using your raster image:
im = imread('SampleA_128x3_#1.png');
%Define thresholds for segmentation
threshold1 = 48; % Threshold for class 1
threshold2 = 58; % Threshold for class 2
% Apply segmentation
outputImage = zeros(size(im)); % Initialize segmented image
outputImage(im <= threshold1) = 1; % Class 1
outputImage(im > threshold1 & im <= threshold2) = 2; % Class 2
outputImage(im > threshold2) = 3; % Class 3
% display thresholded image with scaling
imagesc(outputImage);
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1675186/image.png)
2 Comments
Walter Roberson
on 22 Apr 2024
Change to
outputImage = zeros(size(A), 'uint8'); % Initialize segmented image
and imwrite() outputImage
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!