How to save the segmented image automatically - matlab

I did a program on matlab for character segmentation of bengali script and i want to save the series of segmented image automatically in a specific folder. So anyone help me with the matlab code for saving image automatic
%%LINES SEGMENTATION:
close all;
clear all;
clc;
im=imread('page_1.tif');%read the image
%figure, imshow(im);
%%title('INPUT IMAGE WITH NOISE');
qw=im;
if size(im,3)==3 % RGB image %% Convert to gray scale
im=rgb2gray(im);
end
threshold = graythresh(im); %% Convert to binary image
im =~im2bw(im,threshold);
im = bwareaopen(im,10); %% Remove all object containing fewer than 60 pixels
%figure(2) %% Show image binary image
%imshow(~im);
%title('INPUT IMAGE WITHOUT NOISE');
%figure, area(im);
%find Area of Interest:
a=(~im);
ijk=~a;
xy=sum(ijk,2);
measurements = regionprops(xy == 0, 'Area', 'PixelIdxList');
%Get indexes of those regions that are >= 20 in length.
fiveLongRegions = find([measurements.Area] >= 3);
theIndexes = vertcat(measurements(fiveLongRegions).PixelIdxList);
c=a;
c(theIndexes,:)=0;
%figure, imshow(c);
%title('AREA OF INTEREST FOR LINE SEGMENT');
ca=~c;
%Segmentation of line:
[x,y]=size(ca);
mat1=sum(ca,2);%sum the elements of bwrowise and save into column matrix mat1
mat2=y-mat1;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3=mat2~=0;
mat4=diff(mat3);
index1=find(mat4);
[q,w]=size(index1);%size of index2 matrix is q*w
kap=1;
lam=1;
%iii=1;
%ii=1;
while kap<((q/2)+1);%number of loops=number of lines
k=1;
mat5=([]);
for j=(index1(lam)+1):1:index1(lam+1)
mat5(k,:)=c(j,:); %store the line segmented matrix
k=k+1;
end
lam=lam+2;
kap=kap+1;
figure, imshow(mat5);
%%imsave();
%%WORDS SEGMENTATION:
bwword=im2bw(mat5);%convert the image im into binary(black and white)
aword=~bwword;
bword=sum(aword,1);
%%figure, area(b);
%%Measure lengths of all "0" regions.
measurementsword = regionprops(bword == 0, 'Area', 'PixelIdxList');
% Get indexes of those regions that are >= 20 in length.
fiveLongRegionsword = find([measurementsword.Area] >= 5);
theIndexesword = vertcat(measurementsword(fiveLongRegionsword).PixelIdxList);
cword=aword;
cword(:,theIndexesword)=1;
%%figure, imshow(c);
dword=~cword;
%%figure, imshow(dword);
%%title('AREA OF INTERESRT FOR WORD SEGMENTATION IMAGE');
[xword,yword]=size(cword);
mat1word=sum(cword,1);%sum the elements of bwrowise and save into column matrix mat1
mat2word=xword-mat1word;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3word=mat2word~=0;
mat4word=diff(mat3word);
index1word=find(mat4word);
[qword,wword]=size(index1word);%size of index2 matrix is q*w
kapword=1;
lamword=1;
%%iii=1;
%%ii=1;
while kapword<((wword/2)+1);%number of loops=number of lines
kword=1;
mat5word=([]);
for jword=(index1word(lamword)+1):1:index1word(lamword+1)
mat5word(:,kword)=bwword(:,jword); %store the word segmented matrix
kword=kword+1;
end
lamword=lamword+1;
kapword=kapword+1;
figure, imshow(mat5word);
%imsave();
%%CHARACTER SEGMENTATION:
bwcha=im2bw(mat5word);%convert the image im into binary(black and white)
acha=~bwcha;
mat1cha=sum(a,2);
%figure, area(mat1);
xcha=find(mat1cha>70);
ycha=acha;
ycha(xcha,:)=0;
ycha = bwareaopen(ycha,20);
figure,imshow(ycha);
%figure, area(y);
%mat2=sum(y,2);
%x1=find(mat2<7);
%y1=y;
%y1(x1,:)=0;
%y1 = bwareaopen(y1,15);
%z=~y1;
%figure, imshow(z);
[Lcha, bcha,]=bwlabel(ycha); %% Label connected components
propiedcha=regionprops(Lcha,'BoundingBox'); %% Measure properties of image regions
for ncha=1:size(propiedcha,1) %% Plot Bounding Box
rectangle('Position',propiedcha(ncha).BoundingBox,'EdgeColor','g','LineWidth',1);
end
for ncha=1:bcha %% Objects extraction
[rcha,ccha] = find(Lcha==ncha);
n1cha=ycha(min(rcha):max(rcha),min(ccha):max(ccha));
figure, imshow(~n1cha);
%pause(0.2)
%imsave();
end
end
end
`enter co%%LINES SEGMENTATION:
close all;
clear all;
clc;
im=imread('page_1.tif');%read the image
%figure, imshow(im);
%%title('INPUT IMAGE WITH NOISE');
qw=im;
if size(im,3)==3 % RGB image %% Convert to gray scale
im=rgb2gray(im);`enter code here`
end
threshold = graythresh(im); %% Convert to binary image
im =~im2bw(im,threshold);
im = bwareaopen(im,10); %% Remove all object containing fewer than 60 pixels
%figure(2) %% Show image binary image
%imshow(~im);
%title('INPUT IMAGE WITHOUT NOISE');
%figure, area(im);
%find Area of Interest:
a=(~im);
ijk=~a;
xy=sum(ijk,2);
measurements = regionprops(xy == 0, 'Area', 'PixelIdxList');
%Get indexes of those regions that are >= 20 in length.
fiveLongRegions = find([measurements.Area] >= 3);
theIndexes = vertcat(measurements(fiveLongRegions).PixelIdxList);
c=a;
c(theIndexes,:)=0;
%figure, imshow(c);
%title('AREA OF INTEREST FOR LINE SEGMENT');
ca=~c;
%Segmentation of line:
[x,y]=size(ca);
mat1=sum(ca,2);%sum the elements of bwrowise and save into column matrix mat1
mat2=y-mat1;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3=mat2~=0;
mat4=diff(mat3);
index1=find(mat4);
[q,w]=size(index1);%size of index2 matrix is q*w
kap=1;
lam=1;
%iii=1;
%ii=1;
while kap<((q/2)+1);%number of loops=number of lines
k=1;
mat5=([]);
for j=(index1(lam)+1):1:index1(lam+1)
mat5(k,:)=c(j,:); %store the line segmented matrix
k=k+1;
end
lam=lam+2;
kap=kap+1;
figure, imshow(mat5);
%%imsave();
%%WORDS SEGMENTATION:
bwword=im2bw(mat5);%convert the image im into binary(black and white)
aword=~bwword;
bword=sum(aword,1);
%%figure, area(b);
%%Measure lengths of all "0" regions.
measurementsword = regionprops(bword == 0, 'Area', 'PixelIdxList');
% Get indexes of those regions that are >= 20 in length.
fiveLongRegionsword = find([measurementsword.Area] >= 5);
theIndexesword = vertcat(measurementsword(fiveLongRegionsword).PixelIdxList);
cword=aword;
cword(:,theIndexesword)=1;
%%figure, imshow(c);
dword=~cword;
%%figure, imshow(dword);
%%title('AREA OF INTERESRT FOR WORD SEGMENTATION IMAGE');
[xword,yword]=size(cword);
mat1word=sum(cword,1);%sum the elements of bwrowise and save into column matrix mat1
mat2word=xword-mat1word;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3word=mat2word~=0;
mat4word=diff(mat3word);
index1word=find(mat4word);
[qword,wword]=size(index1word);%size of index2 matrix is q*w
kapword=1;
lamword=1;
%%iii=1;
%%ii=1;
while kapword<((wword/2)+1);%number of loops=number of lines
kword=1;
mat5word=([]);
for jword=(index1word(lamword)+1):1:index1word(lamword+1)
mat5word(:,kword)=bwword(:,jword); %store the word segmented matrix
kword=kword+1;
end
lamword=lamword+1;
kapword=kapword+1;
figure, imshow(mat5word);
%imsave();
%%CHARACTER SEGMENTATION:
bwcha=im2bw(mat5word);%convert the image im into binary(black and white)
acha=~bwcha;
mat1cha=sum(a,2);
%figure, area(mat1);
xcha=find(mat1cha>70);
ycha=acha;
ycha(xcha,:)=0;
ycha = bwareaopen(ycha,20);
figure,imshow(ycha);
%figure, area(y);
%mat2=sum(y,2);
%x1=find(mat2<7);
%y1=y;
%y1(x1,:)=0;
%y1 = bwareaopen(y1,15);
%z=~y1;
%figure, imshow(z);
[Lcha, bcha,]=bwlabel(ycha); %% Label connected components
propiedcha=regionprops(Lcha,'BoundingBox'); %% Measure properties of image regions
for ncha=1:size(propiedcha,1) %% Plot Bounding Box
rectangle('Position',propiedcha(ncha).BoundingBox,'EdgeColor','g','LineWidth',1);
end
for ncha=1:bcha %% Objects extraction
[rcha,ccha] = find(Lcha==ncha);
n1cha=ycha(min(rcha):max(rcha),min(ccha):max(ccha));
figure, imshow(~n1cha);
%pause(0.2)
%imsave();
end
end
end
de here`ally i am providing my code

Assuming you are trying to write to folder all n1cha images that you show at the end of your code.
You'll need to maintain a counter that counts how many characters you already saved and then use imwrite to save the characters:
% init variables before loop
imgFolder = 'path/to/saved/images';
counter = 1;
while kap<((q/2)+1);%number of loops=number of lines
% your code here... nested loops...
% ...
% finally you get to this loop:
for ncha=1:bcha
% extract the character...
imwrite( n1cha, fullfile( imgFolder, sprintf( 'char_%04d.png', counter ) ) );
counter = counter + 1;
end
end

If you want to save it to folder with name 'Folder', here it goes(I'm using and copy paste your code):
folder = "Folder"; // **the path and name of your folder**<br/>
for ncha=1:bcha %% Objects extraction<br/>
[rcha,ccha] = find(Lcha==ncha);<br/>
n1cha=ycha(min(rcha):max(rcha),min(ccha):max(ccha));<br/>
figure, imshow(~n1cha);<br/>
imwrite(n1cha, folder); **//code to save it to folder 'Folder' automatically**<br/>
end

Related

moving shadow elimination in video

I wish to remove moving shadow in video. I followed the steps as mentioned in this article, but getting the same result before and after applying threshold operation on the swt output. didn't get the expected output...Can anyone suggest me what I am doing wrong?
Steps to do for shadow removal:
(i) Read the video.
(ii) After the color conversion split the h s v components
(iii) applying the stationary wavelet transform on on s and v components of frame
(iv) calculate skew value for respective swt output of s and v component
(v) Assign the value 1 and 0 to 's and v' pixel if swt of v is greater than skewness value of v likewise for s too.
(vi) Do inverse swt over the s and v
(vii)Combine the h s and v
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 22;
movieFullFileName = fullfile('cam4v.mp4');
% Check to see that it exists.
if ~exist(movieFullFileName, 'file')
strErrorMessage = sprintf('File not found:\n%s\nYou can choose a new one,
or cancel', movieFullFileName);
response = questdlg(strErrorMessage, 'File not found', 'OK - choose a new
movie.', 'Cancel', 'OK - choose a new movie.');
if strcmpi(response, 'OK - choose a new movie.')
[baseFileName, folderName, FilterIndex] = uigetfile('*.avi');
if ~isequal(baseFileName, 0)
movieFullFileName = fullfile(folderName, baseFileName);
else
return;
end
else
return;
end
end
try
videoObject = VideoReader(movieFullFileName);
% Determine how many frames there are.
numberOfFrames = videoObject.NumberOfFrames;
vidHeight = videoObject.Height;
vidWidth = videoObject.Width;
numberOfFramesWritten = 0;
% Prepare a figure to show the images in the upper half of the screen.
figure;
% screenSize = get(0, 'ScreenSize');
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Ask user if they want to write the individual frames out to disk.
promptMessage = sprintf('Do you want to save the individual frames out to
individual disk files?');
button = questdlg(promptMessage, 'Save individual frames?', 'Yes', 'No',
'Yes');
if strcmp(button, 'Yes')
writeToDisk = true;
% Extract out the various parts of the filename.
[folder, baseFileName, extentions] = fileparts(movieFullFileName);
% Make up a special new output subfolder for all the separate
% movie frames that we're going to extract and save to disk.
% (Don't worry - windows can handle forward slashes in the folder
name.)
folder = pwd; % Make it a subfolder of the folder where this m-file
lives.
outputFolder = sprintf('%s/Movie Frames from %s', folder,
baseFileName);
% Create the folder if it doesn't exist already.
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
else
writeToDisk = false;
end
% Loop through the movie, writing all frames out.
% Each frame will be in a separate file with unique name.
for frame = 1 : numberOfFrames
% Extract the frame from the movie structure.
thisFrame = read(videoObject, frame);
% Display it
hImage = subplot(2, 2, 1);
image(thisFrame);
caption = sprintf('Frame %4d of %d.', frame, numberOfFrames);
title(caption, 'FontSize', fontSize);
drawnow; % Force it to refresh the window.
% Write the image array to the output file, if requested.
if writeToDisk
% Construct an output image file name.
outputBaseFileName = sprintf('Frame %4.4d.png', frame);
outputFullFileName = fullfile(outputFolder, outputBaseFileName);
% Stamp the name and frame number onto the image.
% At this point it's just going into the overlay,not actually
getting written into the pixel values.
text(5, 15, outputBaseFileName, 'FontSize', 20);
% Extract the image with the text "burned into" it.
frameWithText = getframe(gca);
% frameWithText.cdata is the image with the text
% actually written into the pixel values.
% Write it out to disk.
imwrite(frameWithText.cdata, outputFullFileName, 'png');
end
if frame == 1
xlabel('Frame Number');
ylabel('Gray Level');
% Get size data later for preallocation if we read
% the movie back in from disk.
[rows, columns, numberOfColorChannels] = size(thisFrame);
end
% Update user with the progress. Display in the command window.
if writeToDisk
progressIndication = sprintf('Wrote frame %4d of %d.', frame,
numberOfFrames);
else
progressIndication = sprintf('Processed frame %4d of %d.', frame,
numberOfFrames);
end
disp(progressIndication);
% Increment frame count (should eventually = numberOfFrames
% unless an error happens).
numberOfFramesWritten = numberOfFramesWritten + 1;
% Now let's do the differencing
alpha = 0.5;
if frame == 1
Background = thisFrame;
else
% Change background slightly at each frame
% Background(t+1)=(1-alpha)*I+alpha*Background
Background = (1-alpha)* thisFrame + alpha * Background;
end
% Display the changing/adapting background.
subplot(2, 2, 3);
imshow(Background);
title('Adaptive Background', 'FontSize', fontSize);
% Do color conversion from rgb to hsv
x=rgb2hsv(thisFrame);
y=rgb2hsv(Background);
% Split the hsv component to h,s,v value
Hx = x(:,:,1); Hy = y(:,:,1);
Sx = x(:,:,2); Sy = y(:,:,2);
Vx = x(:,:,3); Vy = y(:,:,3);
%Find the absolute diffrence between h s v value of current and
previous frame
dh=(abs(double(Hx) - double(Hy)));
ds1=(abs(double(Sx) - double(Sy)));
dv1=(abs(double(Vx) - double(Vy)));
%Perform the swt2 transformation on difference of s and v value
[as,hs,vs,ds] = swt2(ds1,1,'haar');
[av,hv,vv,dv] = swt2(dv1,1,'haar');
%Compute the skewness value of 'swt of v'
sav=skewness(av(:));
shv=skewness(hv(:));
svv=skewness(vv(:));
sdv=skewness(dv(:));
%Compute the skewness value of 'swt of s'
sas=skewness(as(:));
shs=skewness(hs(:));
svs=skewness(vs(:));
sds=skewness(ds(:));
% Do the shadow detection based on the output of swt and skew of 'v'
value
% Compare swt v output with its skew value if the av >=sav then av is
assigned to one else it becomes zero.This operation continues till variable i
b=(av>=sav); f= (as>=sas);
c=(hv>=shv); g=(hs>=shs);
d=(vv>=svv); h=(vs>=svs);
e=(dv>=sdv); i=(ds>=sds);
% Remove the shadows based on 'and operation
j=(b&f); l=(d&h);
k=(c&g); m=(e&i);
% Do inverse swt operation
recv = iswt2(b,c,d,e,'haar');
recs= iswt2(j,k,l,m,'haar');
%Combine the value of h,s and v
de_shadow=cat(3,dh,recs,recv);
rgb=hsv2rgb(de_shadow);
% Plot the image.
subplot(2, 2, 4);
imshow(rgb);
title('output Image', 'FontSize', fontSize);
end
% Alert user that we're done.
if writeToDisk
finishedMessage = sprintf('Done! It wrote %d frames to
folder\n"%s"', numberOfFramesWritten, outputFolder);
else
finishedMessage = sprintf('Done! It processed %d frames of\n"%s"',
numberOfFramesWritten, movieFullFileName);
end
disp(finishedMessage); % Write to command window.
uiwait(msgbox(finishedMessage)); % Also pop up a message box.
% Exit if they didn't write any individual frames out to disk.
if ~writeToDisk
return;
end
% Ask user if they want to read the individual frames from the disk,
% that they just wrote out, back into a movie and display it.
promptMessage = sprintf('Do you want to recall the individualframes\nback
from disk into a movie?\n(This will take several seconds.)');
button = questdlg(promptMessage, 'Recall Movie?', 'Yes', 'No', 'Yes');
if strcmp(button, 'No')
return;
end
% Create a VideoWriter object to write the video out to a new, different
file.
writerObj = VideoWriter('Newcam4v.mp4');
open(writerObj);
% Read the frames back in from disk, and convert them to a movie.
% Preallocate recalledMovie, which will be an array of structures.
% First get a cell array with all the frames.
allTheFrames = cell(numberOfFrames,1);
allTheFrames(:) = {zeros(vidHeight, vidWidth, 3, 'uint8')};
% Next get a cell array with all the colormaps.
allTheColorMaps = cell(numberOfFrames,1);
allTheColorMaps(:) = {zeros(256, 3)};
% Now combine these to make the array of structures.
recalledMovie = struct('cdata', allTheFrames, 'colormap',allTheColorMaps)
for frame = 1 : numberOfFrames
% Construct an output image file name.
outputBaseFileName = sprintf('Frame %4.4d.png', frame);
outputFullFileName = fullfile(outputFolder, outputBaseFileName);
% Read the image in from disk.
thisFrame = imread(outputFullFileName);
% Convert the image into a "movie frame" structure.
thisFrame=imresize(thisFrame,[452, 231]);
recalledMovie(frame) = im2frame(thisFrame);
% Write this frame out to a new video file.
writeVideo(writerObj, thisFrame);
end
close(writerObj);
% Get rid of old image and plot.
delete(hImage);
% Create new axes for our movie.
subplot(1, 3, 2);
axis off; % Turn off axes numbers.
title('Movie recalled from disk', 'FontSize', fontSize);
% Play the movie in the axes.
movie(recalledMovie);
% Note: if you want to display graphics or text in the overlay
% as the movie plays back then you need to do it like I did at first
% (at the top of this file where you extract and imshow a frame at a
time.)
msgbox('Done this experiment!');
catch ME
% Some error happened if you get here.
strErrorMessage = sprintf('Error extracting movie frames
from:\n\n%s\n\nError: %s\n\n)', movieFullFileName, ME.message);
uiwait(msgbox(strErrorMessage));
end

Can anyone suggest how do I obtain all the values of the variable bc?

The variable bc is getting overwritten and I am Unable to plot all the values of the variable from the start.
I tried exporting the variable to a csv file but that didn't work.
I'm trying to detect a red, green, blue object and plot its coordinates versus time in matlab.
a = imaqhwinfo;
[camera_name, camera_id, format] = getCameraInfo(a);
% Capture the video frames using the videoinput function
% You have to replace the resolution & your installed adaptor name.
vid = videoinput(camera_name, camera_id, format);
% Set the properties of the video object
set(vid, 'FramesPerTrigger', Inf);
set(vid, 'ReturnedColorspace', 'rgb')
vid.FrameGrabInterval = 5;
%start the video aquisition here
start(vid)
% Set a loop that stop after 100 frames of aquisition
while(vid.FramesAcquired<=100)
% Get the snapshot of the current frame
data = getsnapshot(vid);
% Now to track red objects in real time
% we have to subtract the red component
% from the grayscale image to extract the red components in the image.
diff_im = imsubtract(data(:,:,1), rgb2gray(data));
%Use a median filter to filter out noise
diff_im = medfilt2(diff_im, [3 3]);
% Convert the resulting grayscale image into a binary image.
diff_im = im2bw(diff_im,0.18);
% Remove all those pixels less than 300px
diff_im = bwareaopen(diff_im,300);
% Label all the connected components in the image.
bw = bwlabel(diff_im, 8);
% Here we do the image blob analysis.
% We get a set of properties for each labeled region.
stats = regionprops(bw, 'BoundingBox', 'Centroid');
% Display the image
imshow(data)
hold on
%
% %This is a loop to bound the red objects in a rectangular box.
for object = 1:length(stats)
bb = stats(object).BoundingBox;
bc = stats(object).Centroid;
rectangle('Position',bb,'EdgeColor','r','LineWidth',2)
plot(bc(1),bc(2), '-m+')
x = bc(1);
y = bc(2);
csvwrite('bcx.dat', bc(1));
csvwrite('bcy.dat', bc(2));
a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), ' Y: ', num2str(round(bc(2)))));
set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 12, 'Color', 'yellow');
end
hold off
end
% Both the loops end here.
% Stop the video aquisition.
stop(vid);
% Flush all the image data stored in the memory buffer.
flushdata(vid);
% Clear all variables
clear all
%sprintf('%s','That was all about Image tracking, Guess that was pretty easy :) ')

How do I write RGB values of points selected by roipoly in matlab to a text file?

I did :
I = imread('abc.jpg');
BW = roipoly(I);
I am trying to get the pixel value of all the points that I have clicked while creating a polygon.
r= BW(:, :, 1 );
g= BW(:, :, 2 );
b= BW(:, :, 3 );
This doesn't work.
Finally I would like to write to text file:
filename = fullfile('C:\Users\ABC\Documents\MATLAB','test.txt');
fid = fopen(filename,'w');
fprintf(fid, '%d %d %d', r,g,b);
fclose(fid);
Your problem is that size(BW) is only 2D while I is 3D. BW is only a binary mask indicating what pixels were selected by roipoly.
A possible solution is to use the BW mask to select the pixels from I:
rI = reshape(I,[],3); %// "flatten" the image
selectedRGB = rI(BW,:); %// select the pixels in the polygon
Now you can write to file
dlmwrite( fullfile('C:\Users\ABC\Documents\MATLAB','test.txt'), selectedRGB, 'delimiter', ' ');
See dlmwrite for more info.
If you are only interested in the RGB values of the polygon's corners (and not the entire area), you can use the following code
[BW xi yi] = roipoly(I);
Now you should ignore BW which represent the area, and work only with xi and yi:
sel = sub2ind( size(I(:,:,1)), yi, xi ); %// convert indices to linear indices
selectedRGB = rI(sel,:); %// will give you the RGB of the corners only.
Alternatively, you can use ginput to select points in image.
This code creates points in the corners of the polygon using pixel coordinates,
creats the mask of the region of interest, uses the BW mask to create a grayscale image of the region and then the grayscale region is converted back to RGB.
The text file created in the end of the code contains the Unit8 data of the image.
Is it only the manually specified coordinates all you want to the text file?
I = imread('image.jpg');
c = [62 95 103 70]; % specify column coordinates (more than 4 if you want)
r = [126 122 193 197]; % specify row coordinates (more than 4 if you want)
BW = roipoly(I,c,r); % convert to binary mask
[R C] = size(BW);
for i = 1:R
for j = 1:C
if BW(i,j) == 1
outputImage(i,j) = I(i,j); % get grayscale image of the specified region
else
outputImage(i,j) = 0;
end
end
end
imtool(outputImage, []); % in imtool you can see that pixels have only one value
rgbBinary = cat(3,outputImage,outputImage,outputImage); % convert grayscale image to binary rgb
finalImage = im2uint8(rgbBinary); % convert image from double binary rgb (0 1) to unit8 256 value rgb
imtool(finalImage) % analyze image using (Inspect pixel values)
for i = 1:R
for j = 1:C
if BW(i,j) == 1
finalImage(i,j,1)=I(i,j,1);
finalImage(i,j,2)=I(i,j,2);
finalImage(i,j,3)=I(i,j,3);
end
end
end
imshow(finalImage) % the specified area in rgb
txtdoc = fopen( 'imageData.txt', 'wt' ); % creates txt file if it doesn't exist or overwrites the existing file
dlmwrite('imageData.txt',finalImage,'delimiter',' ') % writes the data to txt file delimited by space
fclose(txtdoc);

connected component analysis in MATLAB

I want to apply connected component analysis on a grey scale image with considering pixels whose grey level is more than a threshold. then, I want to remove those connected components whose length is less than a threshold. please help me? I wrote following code in MATLAB, is it efficient?
thank you in advance.
%im = input image;
% alpha1 = 0.0001;
% alpha2 = 0.0001;
% [row col] = size(im);
%
%
% thr1 = mean(mean(im))-alpha1*std(std(im));
% BW = zeros(size(im));
%
% for rr = 1:row
% for cc = 1:col
% if im(rr,cc)>thr2
% BW(rr,cc) = 1;
% else
% BW(rr,cc) = 0;
% end
% end
% end
%
% CC = bwconncomp(BW);
% area_in_pixels = cellfun(#length,CC.PixelIdxList);
% thr2 = mean(area_in_pixels)-alpha2*std(area_in_pixels);
% idx = find(area_in_pixels <= thr3);
% for kk = 1:length(idx)
% aaa = idx(kk);
% BW(CC.PixelIdxList{aaa})=0;
% end
You can try regionprops instead to extract all objects in your image. With the code below you get the positions of all objects smaller than a threshold which you can manipulate or do what you need to do afterwards...
Comparably you can go through the different objects and extract the grey level and if it is below a threshold manipulate them.
% Threshold for the size in pixels that you want
threshold = 100;
% read your image
rawimage = imread('yourimage.jpg');
% create a 2D field by summing
im = sum(rawimage,3);
% label all objects that have 8 neighbours
IMAGE_labeled = bwlabel(im,8);
% get the properties of all elements
shapedata=regionprops (IMAGE_labeled,'all');
% get those elements that are smaller in size (area) than the threshold
index = find(cell2mat({shapedata(:).Area})<=threshold);
% make a contourplot of im
figure
contourf(im)
hold on
% creation of colormap with the size of all identified objects below the thres
mycolormap = jet(size(index,2));
% loop over all small objects, extraction of their position in the original file, plotting circles with different colors at the position of each small object
imap = 1;
mean_of_red = zeros(length(index),1);
for i = index
plot (shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,2),'o','MarkerFaceColor',mycolormap(imap,:))
mean_of_red(i) = mean(mean(im(shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,1),1)));
imap=imap+1;
end

how to plot the histogram of the segmented line of document images

I am writing a program for line segmentation and I want to plot a horizontal histogram of the input image and the segmented lines, but I don't know the code for plotting histograms. Please help me, I have given my program below:
close all;
clear all;
clc;
im=imread('test_img.tif');%read the image
figure, imshow(im);
title('INPUT IMAGE WITH NOISE');
area(im)
if size(im,3)==3 % RGB image %% Convert to gray scale
im=rgb2gray(im);
end
threshold = graythresh(im); %% Convert to binary image
im =~im2bw(im,threshold);
im = bwareaopen(im,15); %% Remove all object containing fewer than 60 pixels
figure(2) %% Show image binary image
imshow(~im);
title('INPUT IMAGE WITHOUT NOISE')
%find Area of Interest:
a=(~im);
ijk=~a;
xy=sum(ijk,2);
measurements = regionprops(xy == 0, 'Area', 'PixelIdxList');
% Get indexes of those regions that are >= 20 in length.
fiveLongRegions = find([measurements.Area] >= 5);
theIndexes = vertcat(measurements(fiveLongRegions).PixelIdxList);
c=a;
c(theIndexes,:)=0;
figure, imshow(c);
title('AREA OF INTEREST FOR LINE SEGMENT');
%Segmentation of line:
[x,y]=size(a);
mat1=sum(a,2);%sum the elements of bwrowise and save into column matrix mat1
mat2=y-mat1;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3=mat2~=0;
mat4=diff(mat3);
index1=find(mat4);
[q,w]=size(index1);%size of index2 matrix is q*w
kap=1;
lam=1;
%iii=1;
%ii=1;
while kap<((q/2)+1);%number of loops=number of lines
k=1;
mat5=([]);
for j=(index1(lam)+1):1:index1(lam+1)
mat5(k,:)=a(j,:); %store the line segmented matrix
k=k+1;
end
lam=lam+2;
kap=kap+1;
figure, imshow(mat5);
imsave();
end