Segment Image and Save as New Picture

2 views (last 30 days)
StardustDragon on 18 Oct 2021
Answered: yanqi liu on 19 Oct 2021
Assuming I can segment an image using a process like this: Texture Segmentation Using Gabor Filters - MATLAB & Simulink (
How can I save the image of the segmented dog (see bottom of that link) and save into a jpg? Without the black background, just the dog itself?

Accepted Answer

yanqi liu
yanqi liu on 19 Oct 2021
sir,please check the follow code to get some information
clc; clear all; close all;
A = imread('kobi.png');
A = imresize(A,0.25);
Agray = rgb2gray(A);
imageSize = size(A);
numRows = imageSize(1);
numCols = imageSize(2);
wavelengthMin = 4/sqrt(2);
wavelengthMax = hypot(numRows,numCols);
n = floor(log2(wavelengthMax/wavelengthMin));
wavelength = 2.^(0:(n-2)) * wavelengthMin;
deltaTheta = 45;
orientation = 0:deltaTheta:(180-deltaTheta);
g = gabor(wavelength,orientation);
gabormag = imgaborfilt(Agray,g);
for i = 1:length(g)
sigma = 0.5*g(i).Wavelength;
K = 3;
gabormag(:,:,i) = imgaussfilt(gabormag(:,:,i),K*sigma);
X = 1:numCols;
Y = 1:numRows;
[X,Y] = meshgrid(X,Y);
featureSet = cat(3,gabormag,X);
featureSet = cat(3,featureSet,Y);
numPoints = numRows*numCols;
X = reshape(featureSet,numRows*numCols,[]);
X = bsxfun(@minus, X, mean(X));
X = bsxfun(@rdivide,X,std(X));
coeff = pca(X);
feature2DImage = reshape(X*coeff(:,1),numRows,numCols);
L = kmeans(X,2,'Replicates',5);
L = reshape(L,[numRows numCols]);
L = reshape(L,[numRows numCols]);
Aseg1 = zeros(size(A),'like',A);
Aseg2 = zeros(size(A),'like',A);
BW = L == 2;
BW = ~BW;
BW = bwareafilt(BW,1);
if BW(round(size(BW,1)/2), round(size(BW,2)/2))==0
BW = ~BW;
[r,c] = find(BW);
A1 = A(:,:,1); A2 = A(:,:,2); A3 = A(:,:,3);
A1(~BW) = 255;
A2(~BW) = 255;
A3(~BW) = 255;
B = cat(3, A1, A2, A3);
B = B(min(r):max(r),min(c):max(c),:);
figure; imshow(B);
% save
imwrite(mat2gray(B), 'result.png');

More Answers (1)

DGM on 19 Oct 2021
You can't have an image of "just the dog", in the sense that the image must be a rectangular array. The background must be something. You can fill it with a solid color, or probably what you intend is to use an alpha mask to make the background transparent.
inpict = imread('coins.png');
mask = imread('coinmask.png');
clf % to reset web-view
Imshow(), etc doesn't handle transparent image display.

Community Treasure Hunt

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

Start Hunting!