Question:

I'm trying to create a mask (or similar result) in order to erase pieces of a binary image that are not attached to the object surrounded by the boundary. I saw this thread (http://www.mathworks.com/matlabcentral/answers/120579-converting-boundary-to-mask) to do this from bwboundaries, but I'm having trouble making suitable changes to it. My goal is to use this code to isolate the part of this topography map that is connected, and get rid of the extra pieces. I need to retain the structure inside of the bounded area, as I was then going to use bwboundaries to create additional boundary lines of the main object's "interior" structure.

The following is my code to first create the single boundary line by searching for the bottom left pixel of the black area to begin the trace. It just looks for the first column of the image that isn't completely white and selects the last black pixel. The second section was then to create the inner boundary lines. Note that I am attempting this two step process, but if there is a way to do it with only one I'd like to hear that solution as well. Ultimately I just want boundaries for the main, large black area and the holes inside of it, while getting rid of the extra pieces hanging around.

`````` figName='Images/BookTrace_1';

BW=im2bw(BW);
imshow(BW,[]);

for j=1:size(BW,2)
if sum(BW(:,j))~=sum(BW(:,1))
corner=BW(:,j);
c=j-1;
break
end
end
r=find(corner==0);
r=r(end);

outline = bwtraceboundary(BW,[r c],'W',8,Inf,'counterclockwise');
hold on;
plot(outline(:,2),outline(:,1),'g','LineWidth',2);

[B,L] = bwboundaries(BW);
hold on
for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 2)
end
``````

Any suggestions or tips are greatly appreciated. If there are questions, please let me know and I'll update the post. Thank you!

EDIT: For clarification, my end goal is as in the below image. I need to trace all of the outer and inner boundaries attached to the main object, while eliminating any spare small pieces that are not attached to it.

It's very simple. I actually wouldn't use the code above and use the image processing toolbox instead. There's a built-in function to remove any white pixels that touch the border of the image. Use the `imclearborder` function.

The function will return a new binary image where any pixels that were touching the borders of the image will be removed. Given your code, it's very simply:

``````out = imclearborder(BW);
``````

Using the above image as an example, I'm going to threshold it so that the green lines are removed... or rather merged with the other white pixels, and I'll call the above function:

``````BW = imread('http://i.stack.imgur.com/jhLOw.png'); %// Read from StackOverflow
BW = im2bw(BW); %// Convert to binary
out = imclearborder(BW); %// Remove pixels along border
imshow(out); %// Show image
``````

We get:

If you want the opposite effect, where you want to retain the boundaries and remove everything else inside, simply create a new image by copying the original one and use the output from the above to null these pixel locations.

``````out2 = BW; %// Make copy
out2(out) = 0; %// Set pixels not belonging to boundary to 0
imshow(out2); %// Show image
``````

We thus get:

Edit

Given the above desired output, I believe I know what you want now. You wish to fill in the holes for each group of pixels and trace along the boundary of the desired result. The fact that we have this split up into two categories is going to be useful. For those objects that are in the interior, use the `imfill` function and specify the `holes` option to fill in any of the black holes so that they're white. For the objects that exterior, this will need a bit of work. What I would do is invert the image so that pixels that are black become white and vice-versa, then use the `bwareaopen` function to clear away any pixels whose area is below a certain amount. This will remove those small isolated black regions that are along the border of the exterior regions. Once you're done, re-invert the image. The effect of this is that the small holes will be eliminated. I chose a threshold of 500 pixels for the area... seems to work well.

Therefore, using the above variables as reference, do this:

``````%// Fill holes for both regions separately
out_fill = imfill(out, 'holes');
out2_fill = ~bwareaopen(~out2, 500);

%// Merge together
final_out = out_fill | out2_fill;
``````

This is what we get:

If you want a nice green border like in your example to illustrate this point, you can do this:

``````perim = bwperim(final_out);
red = final_out;
green = final_out;
blue = final_out;
red(perim) = 0;
blue(perim) = 0;
out_colour = 255*uint8(cat(3, red, green, blue));
imshow(out_colour);
``````

The above code finds the perimeter of the objects, then we create a new image where the red and blue channels along the perimeter are set to 0, while setting the green channel to 255.

We get this:

You can ignore the green pixel border that surrounds the image. That's just a side effect with the way I'm finding the perimeter along the objects in the image. In fact, the image you supplied to me had a white pixel border that surrounds the whole region, so I'm not sure if that's intended or if that's part of the whole grand scheme of things.

To consolidate into a working example so that you can copy and paste into MATLAB, here's all of the code in one code block:

``````%// Pre-processing
BW = im2bw(BW); %// Convert to binary

out = imclearborder(BW); %// Remove pixels along border

%// Obtain pixels that are along border
out2 = BW; %// Make copy
out2(out) = 0; %// Set pixels not belonging to boundary to 0

%// Fill holes for both regions separately
out_fill = imfill(out, 'holes');
out2_fill = ~bwareaopen(~out2, 500);

%// Merge together
final_out = out_fill | out2_fill;

%// Show final output
figure;
imshow(final_out);

%// Bonus - Show perimeter of output in green
perim = bwperim(final_out);
red = final_out;
green = final_out;
blue = final_out;
red(perim) = 0;
blue(perim) = 0;
out_colour = 255*uint8(cat(3, red, green, blue));
figure;
imshow(out_colour);
``````

Related:

html,ruby-on-rails,image,ruby-on-rails-4,svg
I am trying to replace the tag with link_to in my rails application view. for replacing I have svg icon, text and link all in one tag. Here is below <a class="navbar-brand" href="index.html"><%= image_tag 'logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;" %> My Project </a> but I...

Change Background image in WPF using C# [duplicate]

c#,wpf,image,background,resources
This question already has an answer here: Change WPF window background image in C# code 3 answers I'd like to change the background image of my WPF application by a button. I know how to do it using WindowsForms, but in WPF I failed. I found a solution already,...

Excel VBA 2013 Print Image

image,excel-vba,printing
I would like to print an image that shows in a frame on a userform. frame1.Picture = LoadPicture(spath & xPicture & ".jpg") spath is the full path to where the picture is stored. This shows the picture just fine. Now I would like to be able to print it. Is...

Trouble generating Barcode using ZXing library with large data

java,android,image,barcode,zxing
I need to generate barcode in 128A format with data: 900000588548001100001305000000000207201512345.6|12345.7 I'm using ZXing library and Here is my method: private void barcodeGenerator(String data) { try { com.google.zxing.MultiFormatWriter writer = new MultiFormatWriter(); BitMatrix bm = writer.encode(data, BarcodeFormat.CODE_128, 700, 200); Bitmap ImageBitmap = Bitmap.createBitmap(700, 200, Config.ARGB_8888); for (int i = 0;...

how to calculate probability for each class for predicate with knn without fitcknn?

matlab
my matlab version is 2012a. when I use fitcknn,has this error: Undefined function 'fitcknn' for input arguments of type 'cell'. how to calculate probability for each class for predicate with knn without fitcknn? after use this code, I want to calculate prob_estimates for each neighbors: knn = ClassificationKNN.fit(trainsample, trainlabel,'NumNeighbors',7); y...

matlab plots as movie with legend

matlab,plot,legend,movie
i have a question regarding legend for movies. This is my code: fig = figure(); for i = 1: 70000 plot(signal1) hold on; plot([i,i],[-5,5]) plot(signal2,'r') hold off; title('\fontsize{14} my data'); legend('signal1','signal2'); axis tight; f(i) = getframe(fig); end The legend shows the same colors for the first two things I plot....

How to normalise polynomial coefficients in a fraction?

matlab,polynomial-math
I have the following code: syms z Gc=1.582*(1-0.3679*z^-1)/(1+.418*z^-1); Ghp=.3679*(z^-1)*(1+.718*z^-1)/((1-z^-1)*(1-.3679*z^-1)); T=(Gc*Ghp)/(1+Gc*Ghp); clipboard('copy', latex(simplifyFraction(T))); Which results in following for T: How can I normalise coefficients? I.e. I want the z2 in denominator and z in numerator to have the coefficient of 1. Is there any function in Matlab to do so?...

Matlab — SVM — All Majority Class Predictions with Same Score and AUC = .50

matlab,svm,auc
I'm having a weird problem in training an SVM with an RBF kernel in Matlab. The issue is that, when doing a grid search, using 10-fold cross-validation, for the C and Sigma values I always get AUC values equal to approximately .50 (varying between .48 and .54 depending) -- I...

Reading all the files in sequence in MATLAB

matlab,image-processing
I am trying to read all the images in the folder in MATLAB using this code flst=dir(str_Expfold); But it shows me output like this. which is not the sequence as i want. Can anyone please tell me how can i read all of them in sequence? for giving downmark, please...

Create string without repeating the same element jn the string (Matlab)

string,matlab
I have a string "FDFACCFFFBDCGGHBBCFGE" . Could anyone help me to generate a new string with the same order but no element inside repeated twice. Thanks ! The expected output should be like this : "FDACBGHE"...

php,mysql,image,png
I have seen loads of other topics and I've tried them all. Can someone please help with why this script won't upload PNG files? Blank PNG image being displayed. \$image = \$_FILES['file']['tmp_name']; \$image_name = \$_FILES['file']['name']; \$ext = pathinfo(\$image_name, PATHINFO_EXTENSION); \$location = "Profiles/{\$user}/Picture/{\$image_name}"; \$new_image = imagecreatetruecolor(100, 100); \$source_image = imagecreatefrompng(\$image); imagealphablending(\$source_image,...

How to force my output data in a inputdlg on Matlab be a double?

matlab,typeconverter
I'm currently using a MATLAB to work and I need some help: I need to convert my output data (variable: units) be a double instead of a cell because I must perform a sum: units = inputdlg(question,title); sum = units + i; I've tried this code also but didn't solve...

How to switch Matlab plot tick labels to scientific form?

matlab,plot
I have a semilogarithmic plot which works so far with semilogx. Now I would like to change the tick labels. Now it says 10^8 10^9 ... 10^13, but I would like to see 1e8, 1e9, ... 1e13 on the x-axis. How can I change that? Cheers Manuel...

How to access variables in the properties block of a Matlab System Object?

I am working on a simple System Object in Matlab/Simulink. It looks like this : classdef realtime_header_detectorSO < matlab.System & matlab.system.mixin.Propagates % correlateHeader % % This template includes the minimum set of functions required % to define a System object with discrete state. properties Header %nrOfBitsInPreviousStep=0; s=100; d=zeros(1,s); end properties...

Python Resize Multiple images ask user to continue

python,xml,image,resize
I'm trying to make a script that resize multiple or a single image based on a data pulled from XML. My question is if i have multiple images how can I print out a qusetion like "There are more than 1 image do you wish to resize image 2 also?......

How to make a Javafx Image Crop App

java,image,canvas,graphics,javafx
I am building an application for my colleagues to crop image. I use FXML with Scene Builder to build the GUI. The user click a button to choose a image from his computer. Then, the image is shown in the GUI. User can zoom and move in the pane. At...

Plot multiple functions on one figure

matlab,matlab-figure
I'm struggling to plot multiple functions on one figure. Here is the code that I have: syms t a; a=0.9514; F1=0.5*sqrt(3*t^2); F2=-0.28375*t^2+1.155*a*(t-a)+1; F3=1; E1=diff(F1,t); E2=diff(F2,t); E3=diff(F3,t); I want to plot E1, E2 and E3, each only within a certain range, to make a "composite" line. I've tried plotting with ezplot...

Images not loaded from master page in directory

asp.net,image
I will make a website whit ASP.NET using C# on the background. I have make my master page with the following image: <img src="afbeeldingen/berichten.png" alt="new messages" /> Because I have a lot of pages in my site, I have make directories in my solution. My problem is now when I...

Creating a cell array of workspace variables without manually writing them all out. MATLAB

matlab
I have 20 column vectors in the workspace and I'd like them all to be contained within a cell array. They're all labelled data1, data2, data3,...data20. Is there a faster way to do this than: cell = {data1, data2, data3, data4, data5, data6, ...} all the way up to data20?...

Crop does not work for gallery images

android,image,crop
I am using the following code to crop images from camera and gallery : private void doCrop() { final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>(); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setType("image/*"); List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0); int size = list.size(); if (size == 0) { Toast.makeText(this, getApplicationContext().getString(R.string.crop_unavailable), Toast.LENGTH_SHORT).show(); // return }...

Matlab - Multiply specific entries by a scalar in multidimensional matrix

matlab,matrix,multidimensional-array,scalar
I'm having problems multiplying specific values within my multidimensional matrix by a scalar. My matrix has the following dimension: size(comDatabe) = 5 10 3 397 10 The third dimension is an x-y-z coordinate frame. Something went wrong and now my y-axis is defined upside down for one subject (#8 out...

Saving images with more than 8 bits per pixel in matlab

image,matlab,image-processing,computer-vision
I need to save a set of pre-processing images in matlab, resulting in grayscale images. The problem is the fact that these pre-processed images have pixel values higher than 255. If I save them with imwrite() as, for instance, .PNG files, does matlab normalize the values to be in [0,255]...

xcorr function with impulse response

matlab,filtering,convolution
I'm trying to design a Wiener filter in Matlab for a deconvolution problem but I'm having a lot of problems. I have a gaussian white noise process with a variance of 1.2 and a impulse response which has length two. Its values are g(0) = 5 and g(1) = 4....

Operating a C++ class from Matlab without mex [closed]

c++,matlab
Is there an alternative way to call a C++ class using MATLAB, and operate its methods on MATLAB variables?

Fetch a saved image and display

ios,image,path
I am developing an App in which I have stored images through imagePicker. now i want to display same images in my collectionView. I got response as a path path=assets/image/155/155_557b1259b8a51.jpg when i add http://xyz.com.assets/image/155/155_557b1259b8a51.jpg then it shows error. How can i get the images through this path.Please Help me out....

MATLAB - How to merge figure sections vertically

matlab,plot
I want to display three figures in a figure window. Assuming that I divide 2x2 regions. subplot(2,2,1) ---------+----------- | R1 | R2 | ---------+----------- | R3 | R4 | ---------+----------- I want to show a figure merging R1 and R3 ant other two in R2 and R4 I can display...

MATLAB Access Classreg

matlab
So, I want to be able to look at (read: copy) MATLAB's NonLinearModel method of printing the regression results to the screen such as this. Nonlinear regression model: y ~ (alpha1 - alpha2*t^0.5) Estimated Coefficients: Estimate SE tStat pValue alpha1 1.0253 0.0082253 124.66 4.8823e-24 alpha2 0.0061783 0.00073277 8.4314 4.4834e-07 Number...

Connecting two binary objects in matlab

matlab,image-processing
I have a binary matrix containing several binary objects and I want to bridge between them. Actually I have the following picture: And the result has to be like this: Is there any function or a shortcut way, other than loops, for this problem?...

Animate through multiple 2D Matlab plots

matlab,plot
I have multiple 2D line plots in Matlab (they represent some wave moving through space). Each plot represents the wave at some time t. I want to animate through these plots (i.e. show the first plot for a fraction of a second, then show the next one, and the next,...

How to solve for matrix in Matlab?

matlab,matrix,least-squares
How can I solve , where and and in the least squares sense in matlab? So I'd like to have the minimizing as output....

Plotting random signal on circle

matlab,plot,signals,circle
I have some random signal (for example sin signal) with the time scale. t=0:0.1:2*pi y=sin(t) plot(t,y) Now I want to draw this signal on this circle. So the time vector actually becomes an envelope of the circle. Envelope of the circle represents "y = 0" in cartesian coordinate system. Here...

two dimensional unique values in Matlab

arrays,matlab
I have two vectors, one of them stores the width dimension of a set of images and another one the height of these set of images. I want to use these values as two dimensional vectors [width height] and store them in a matrix. The first line, for instance, keeps...

javascript,node.js,image,html5-canvas,sails.js
I am using nodejs sails for my app. The app is going to use 50-100 images at some points. I was wondering if someone can point pro and cons of using /assests/images/ folder vs outside repository i.e. AWS S3 for image storing and pulling to draw on the canvas.

Can we add a statement in between MATLAB codes?

matlab
Is it possible to add statements in between the codes. For example: If I have a code like this, r(:,1) = a(:,1) - a(:,2); Then can I write it as, r(:,1) = a(:,1)("this is a constant") - a(:,2)("this is a variable"); ...

Interpolation inside a matrix. Matlab

matlab,matrix
I have a matrix looks like: 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 0 4 0 0 0 0 0 3 0 0 6 0 0 4...

Why black surf from this Matlab command?

matlab,time-frequency
Code tfr = abs ( tfr ); [row_size, column_size] = size(tfr); tfr = tfr(1:round(row_size/2), 1:row_size); surf(tfr); view(2); I get in R2014b of OSX 10.10.3 Yosemite but rotating around shows that the cells should not be black Why is the output black? I wonder if this is a hardware problem or...

what does ellipsis mean in a Matlab function's argument list?

matlab
What is the ellipsis for in this Matlab statement? frame = insertObjectAnnotation(frame, 'rectangle', ... bboxes, labels); ...I could not find in their online doc....

Matlab Distribution Sampling

matlab,distribution,sampling,random-sample
How can I create a vector x in Matlab that has values between 0.8 and 1.2, randomly sampled from a: 1. Uniform 2. Normal distribution? There are a lot of functions dealing with distributions, but I'm having trouble using them properly....

Create mask from bwtraceboundary in Matlab

I'm trying to create a mask (or similar result) in order to erase pieces of a binary image that are not attached to the object surrounded by the boundary. I saw this thread (http://www.mathworks.com/matlabcentral/answers/120579-converting-boundary-to-mask) to do this from bwboundaries, but I'm having trouble making suitable changes to it. My goal...

Preload image for seamless background image change in JavaScript

I have a Python websocket application which sends an image path to a JavaScript HTML file. When the image path is received, I change the background image of the webpage to the supplied image. The issue I'm having at the moment, is when the background changes from the old image...

Dynamically resize side-by-side images with different dimensions to the same height

javascript,html,css,image
I have two images side-by-side within a block-level container with arbitrarily different dimensions (as in, they could be any two images) that I want to dynamically adjust the width of so that the overall height of the two images is the same. I don't think this can be done in...

Giving a string variable as a filename in matlab

string,matlab,filenames
I am using the below mentioned code to get the file names of images according to their id's from images_1 text file as strings and use them to read the images from their directory image_count=1; for image_count=1:6 file=fopen('D:\Academics\New folder\CUB_200_2011\images_1.txt','r'); C = textscan(file, '%s'); original_image=imread('D:\Academics\New folder\CUB_200_2011\images\%s','C{1}{2*(image_count)}'); imshow(original_image) end I am able...

function wait to execute

matlab,events,delay
In Matlab functions can be started at events,but occasionally, like with the resize function, the events are called in rapid order and the function is called many times in succession, which can cause weird behavior and lag. Is there a way to have it listen for the event but only...

php,mysql,image
I have a MySQL table with a column "rounds" and each "rounds" has his own photos. Exemple round1 has photos from start=380 end=385. This means it has 6 photos and the name of the photos contains 380,381,382,383,384 or 385 inside. I use this PHP code to display the photos from...

How to crop image from center using wp_image_editor

wordpress,image,wordpress-plugin,resize-crop,wp-image-editor
I am working on WordPress plugin. In plugin the user upload images from meta field and in back end i use wp_image_editor for cropping and re sizing the images. The images re sized very well but on cropping the images not cropped very well. I give x-dimension 100 and y-dimension...

Why can't I calculate CostFunction J

matlab,machine-learning
This is my implementation of CostFunctionJ: function J = CostFunctionJ(X,y,theta) m = size(X,1); predictions = X*theta; sqrErrors =(predictions - y).^2; J = 1/(2*m)* sum(sqrErrors); But when I try to enter the command in MATLAB as: >> X = [1 1; 1 2; 1 3]; >> y = [1; 2; 3];...

solve symbolic system of equations inside an array

matlab,system,equation
sorry if it already has a answer..i tried other links but it didn't understand i have 2 1*63 array .landa and v. each of their members are syms. and each v member is a function of all landa members.i have already calculated v members and they are all symbolic equations...

thicken an object of image to a curve in matlab

matlab,image-processing
I have a labeled matrix containing two objects. How can I thicken an object to a curve? Actually I have the following image: and I want this: Each pixel of the resulting curve is the median of each column. But if you have another idea, it is acceptable, because I...