Menu
  • HOME
  • TAGS

How to prevent exceeding matrix dimensions while dividing an image into blocks?

Tag: image,matlab,image-processing,image-segmentation

I have an image which I want to divide into overlapping blocks.

I have set the box to be of size 8 rows and 8 columns, and the overlapping factor to be 4 rows/columns.

This is what I have written to solve this:

img = imread('a03-017-05.png');
overlap = 4
count = 1;
for i = 1:overlap:size(img,1)
    for j = 1:overlap:size(img,2)
        new{count} = img(i:i+8,j:j+8);
        count = count+1;
    end
end

This works right until it reaches the end of the image where j+8 or i+8 will go beyond the dimensions of the image. Is there any way to avoid this with minimal data loss?

Thanks

Best How To :

If you simply want to ignore the columns/rows that lie outside full sub-blocks, you just subtract the width/height of the sub-block from the corresponding loop ranges:

overlap = 4
blockWidth = 8;
blockHeight = 8;
count = 1;
for i = 1:overlap:size(img,1) - blockHeight + 1
    for j = 1:overlap:size(img,2) - blockWidth + 1
        ...

Let's say your image is 16x16. The block beginning at column 8 will account for the remainder of the columns, so having a starting index between 9 and 16 is pointless.

Also, I think your example miscalculates the block size... you're getting blocks that are 9x9. I think you want to do:

        new{count} = img(i:i+blockHeight-1,j:j+blockWidth-1);

As an example, in a 13x13 image with the code above, your row indices will be [1, 5] and the row ranges of the blocks will be 1:8 and 5:12. Row/column 13 will be left out.

Python Resize Multiple images ask user to continue

python,xml,image,resize

Change your final loop to: for idx, image in enumerate(imgPath): #img resizing goes here count_remaining = len(imgPath) - (idx+1) if count_remaining > 0: print("There are {} images left to resize.".format(count_remaining)) response = input("Resize image #{}? (Y/N)".format(idx+2)) #use `raw_input` in place of `input` for Python 2.7 and below if response.lower() !=...

xcorr function with impulse response

matlab,filtering,convolution

The following code implements only a part of what I can see in the description. It generates the noise processes and does what is described in the first part. The autocorrelation is not calculated with the filter coefficients but with the actual signal. % generate noise process y y =...

Images not loaded from master page in directory

asp.net,image

@Brendan Hannemann show me a link that where is expaint. The code i must use is: <img src="<%=ResolveUrl("~/afbeeldingen/berichten.png") %>" alt="nieuwe berichten" id="berichten" /> ...

Connecting two binary objects in matlab

matlab,image-processing

Morphological operations are suitable but i would suggest line structuring element as your arrangement is horizontal and you do not want overlaps between lines: clear clc close all BW = im2bw(imread('Silhouette.png')); BW = imclearborder(BW); se = strel('line',10,0); dilateddBW = imdilate(BW,se); img= imerode(BW,se); figure; imshow(img) ...

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

matlab

Not the fastest way, but you could do it as follows: Saving the desired variables in a temporary file Loading that file to get all those variables in a struct array Converting that struct array to a cell array That is, save temp_file -regexp data\d+ %// step 1 allData =...

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

matlab,typeconverter

inputdlg returns a cell array of strings. You can convert to double with str2double: units = str2double(inputdlg(question, title)); ...

Giving a string variable as a filename in matlab

string,matlab,filenames

You would need to change your back slashes \ to forward slashes /, otherwise some \ followed by a letter may be commands in the sprintffunction, like for example \N or \a. See sprintf documentation in the formatSpecarea for more information. original_image=imread(sprintf('D:/Academics/New folder/CUB_200_2011/images/%s', C{1}{2*(image_count)})); ...

two dimensional unique values in Matlab

arrays,matlab

See docs for unique. Assuming widths and heights are column vectors, [C,ia,ic] = unique([widths, heights],'rows') In contrary, if widths and heights are row vectors, [C,ia,ic] = unique([widths; heights].','rows') ...

Matlab Distribution Sampling

matlab,distribution,sampling,random-sample

So, you can use this, for example: y = 0.8 + rand*0.4; this will generate random number between 0.8 and 1.2. because rand creates uniform distribution I believe that rand*0.4 creates the same ;) ...

thicken an object of image to a curve in matlab

matlab,image-processing

This is called "skeletonization" and you can do it with the function bwmorph: bwmorph(Img, 'skel', Inf); Best...

Plotting random signal on circle

matlab,plot,signals,circle

You need to add "noise" to the radius of the circle, roughly around r=1: th = linspace( 0, 2*pi, N ); %// N samples noise = rand( 1, N ) * .1; %// random noise in range [0..0.1] r = 1+noise; %// add noise to r=1 figure; plot( r.*cos(th), r.*sin(th)...

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

javascript,html,css,image

If it's responsive, use percentage heights and widths: html { height: 100%; width: 100%; } body { height: 100%; width: 100%; margin: 0; padding: 0; } div.container { width: 100%; height: 100%; white-space: nowrap; } div.container img { max-height: 100%; } <div class="container"> <img src="http://i.imgur.com/g0XwGQp.jpg" /> <img src="http://i.imgur.com/sFNj4bs.jpg" /> </div>...

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

c++,matlab

You can use calllib to call functions in shared library. This would be the newlib.h #ifdef __cplusplus extern "C"{ #endif void *init(int device); #ifdef __cplusplus } #endif and this would be the newlib.cpp file #include "newlib.h" #include "yourlib.h" A *p; extern "C" void *init(int device) { p = new A;...

Why black surf from this Matlab command?

matlab,time-frequency

My bet is that trf is a very large matrix. In these cases, the surface has so many edges (coloured black by default) that they completely clutter the image, and you don't see the surface patches One solution for that is to remove the edges: surf(trf, 'edgecolor', 'none'). Example: with...

Matlab - Multiply specific entries by a scalar in multidimensional matrix

matlab,matrix,multidimensional-array,scalar

Errr, why you multiply indexes instead of values? I tried this: comDatabe(:,:,[1 2 3],:,8) = comDatabe(:,:,[1 2 3],:,8)*-1 And it worked....

matlab plots as movie with legend

matlab,plot,legend,movie

The strings defined in the legend command are assigned in order of the plots being generated. This means that your first string 'signal1' is assigned to the plot for signal1 and the second string 'signal2' is assigned to the vertical line. You have two possibilities to fix this problem. Execute...

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

string,matlab

Use unique with the 'stable'option: str = 'FDFACCFFFBDCGGHBBCFGE'; result = unique(str, 'stable'); If you want something more manual: use bsxfun to build a logical index of the elements that haven't appeared (~any(...)) before (triu(..., 1)): result = str(~any(triu(bsxfun(@eq, str, str.'), 1))); ...

Excel VBA 2013 Print Image

image,excel-vba,printing

One option is to call Windows Print dialog via shell command. Example: (Full code) Option Explicit Private Declare Function apiShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _ ByVal hwnd As Long, _ ByVal lpOperation As String, _ ByVal lpFile As String, _ ByVal lpParameters As String, _ ByVal lpDirectory As String,...

Uploading PNG to Website Server

php,mysql,image,png

You're not declaring $image_width or $image-height and you are referencing $image instead of $source_image in imagecopyresampled(). I too was getting a plain white image, but after this I get the expected result: $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...

How to switch Matlab plot tick labels to scientific form?

matlab,plot

You can change the XTickLabels property using your own format: set(gca,'XTickLabels',sprintfc('1e%i',0:numel(xt)-1)) where sprintfc is an undocumented function creating cell arrays filled with custom strings and xt is the XTick you have fetched from the current axis in order to know how many of them there are. Example with dummy data:...

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

matlab,simulink

You should be able to use properties s = 100; d = zeros(1,100); end right? If you already have the 100 as a default for s, you should also be able to provide this as part of the default for d. I'm guessing that you're trying to avoid doing that...

Fetch a saved image and display

ios,image,path

if you know the image path or name then you may implement something like this. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ UICollectionViewCell *cell = [[UICollectionViewCell alloc]initWithFrame:CGRectMake(0, 0, 50.0, 50.0)]; cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50.0, 50.0)]; [imageView setImage:[UIImage...

Crop does not work for gallery images

android,image,crop

Try this Working code Buttonclick to take camera dialog.show(); Add this inside Oncreate() captureImageInitialization(); try this it will work // for camera private void captureImageInitialization() { try { /** * a selector dialog to display two image source options, from * camera ‘Take from camera’ and from existing files ‘Select...

MATLAB Access Classreg

matlab

You can read the file using: >> open classreg.regr.modelutils.tstats This will open "tstats.m". The path of that file on your drive can be a acccessed using: >> which classreg.regr.modelutils.tstats In this folder there are all the other m-files which belong to this class....

function wait to execute

matlab,events,delay

The "weird behavior and lag" you see is almost always a result of callbacks interrupting each other's execution, and repeated unnecessary executions of the same callbacks piling up. To avoid this, you can typically set the Interruptible property of the control/component to 'off' instead of the default 'on', and set...

solve symbolic system of equations inside an array

matlab,system,equation

Generally this is done (if the eq is in the format you have) with an Ax=b system. Let me show you how to do it with a simple example of 2 eq with 2 unknowns. 3*l1-4*l2=3 5*l1 -3*l2=-4 You can build the system as: x (unknowns) will be a unknowns...

How to normalise polynomial coefficients in a fraction?

matlab,polynomial-math

You can extract the numerator and denominator with numden, then get their coefficiens with coeffs, normalize the polynomials, and divide again. [n,d] = numden(T); cn = coeffs(n); cd = coeffs(d); T = (n/cn(end))/(d/cd(end)); The output of latex(T) (note: no simplifyFraction now; it would undo things): Of course this isn't equal...

Loading images into html5 canvas

javascript,node.js,image,html5-canvas,sails.js

Yes, use a CDN if you have the option. Pros: - Save enormously on website load time / speed. - Better for organization / maintenance. Cons: - One more paid account; but you may end up having to upgrade your hosting anyway if your images continue to add up with...

Change Background image in WPF using C# [duplicate]

c#,wpf,image,background,resources

Firstly, add a Folder to your Solution (Right click -> Add -> Folder), name it something like "Resources" or something useful. Then, simply add your desired image to the folder (Right click on folder -> Add -> Existing item). Once it's been added, if you click on the image and...

Create mask from bwtraceboundary in Matlab

image,matlab,image-processing,mask,boundary

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...

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

matlab

First, you have to know that fitcknn & ClassificationKNN.fit will end up with the same result. The difference is that fitcknn is a more recent version, so it allows more options. As an example, if you use load fisheriris; X = meas; Y = species; Then this code will work...

How to crop image from center using wp_image_editor

wordpress,image,wordpress-plugin,resize-crop,wp-image-editor

Try this code: $crop = array( 'center', 'center' ); resize( $max_w, $max_h, $crop); ...

How to make a Javafx Image Crop App

java,image,canvas,graphics,javafx

Your question is too much to be answered on StackOverflow. I suggest you start with reading the official Oracle documentation about JavaFX. However, since it's an interesting topic, here's the answer in code. There are several things you need to consider: use an ImageView as container use a ScrollPane in...

Preload image for seamless background image change in JavaScript

javascript,image,preload

You're not actually passing a callback function: NewImage.onload = ImageLoadComplete(); You're passing in the result of calling ImageLoadComplete(), which means you call your callback immediately. Don't call the function and your code should work as expected (most of the time): NewImage.onload = ImageLoadComplete; One issue that you'll encounter is that...

Saving images with more than 8 bits per pixel in matlab

image,matlab,image-processing,computer-vision

You can use the bitdepth parameter to set that. imwrite(img,'myimg.png','bitdepth',16) Of course, not all image formats support all bitdepths, so make sure you are choosing the the right format for your data....

adding link_to with image_tag and image path both

html,ruby-on-rails,image,ruby-on-rails-4,svg

Remove the space after image_tag. <%= link_to '#' do %> My Project <%= image_tag('logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;") %> <% end %> ...

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

matlab,svm,auc

Unless you have some implementation bug (test your code with synthetic, well separated data), the problem might lay in the class imbalance. This can be solved by adjusting the missclassification cost (See this discussion in CV). I'd use the cost parameter of fitcsvm to increase the missclassification cost of the...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

Plot multiple functions on one figure

matlab,matlab-figure

I think you are missing the x limit. xlim([0 2.5*a]) ...

MATLAB - How to merge figure sections vertically

matlab,plot

This is quite simple; just feed into subplot the locations as a vector. For instance, x = -2*pi:0.01:2*pi; subplot(2,2,[1,3]) plot(x,sin(x)) subplot(2,2,2) plot(x,cos(x)) subplot(2,2,4) plot(x,x.^2) gives: ...

Animate through multiple 2D Matlab plots

matlab,plot

I assume with "2d-line" you mean a 2d-plot. This is done by the plot-function, so there is no need of surf or mesh. Sorry, when I got you wrong. The following code does what I think you asked for: % Generate some propagating wave n = 20; t = linspace(0,10,100);...

Can we add a statement in between MATLAB codes?

matlab

You need to comment those statements like this r(:,1) = a(:,1) ... % this is a constant - a(:,2); % this is a variable for more information read this ...

How to solve for matrix in Matlab?

matlab,matrix,least-squares

Rewrite the quantity to minimise as ||Xa - b||^2 = (definition of the Frobenius norm) Tr{(Xa - b) (Xa - b)'} = (expand matrix-product expression) Tr{Xaa'X' - ba'X' - Xab' + bb'} = (linearity of the trace operator) Tr{Xaa'X'} - Tr{ba'X'} - Tr{Xab'} + Tr{bb'} = (trace of transpose of...

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

matlab

http://www.mathworks.com/help/matlab/matlab_prog/continue-long-statements-on-multiple-lines.html Continue Long Statements on Multiple Lines This example shows how to continue a statement to the next line using ellipsis (...). s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ... - 1/6 + 1/7 - 1/8 + 1/9; ...

Why can't I calculate CostFunction J

matlab,machine-learning

As suggested in the comments, the error is because x is of dimension 3x2 and theta of dimension 1x2, so you can't do X*theta. I suspect you want: theta = [0;1]; % note the ; instead of , % theta is now of dimension 2x1 % X*theta is now a...

Trouble generating Barcode using ZXing library with large data

java,android,image,barcode,zxing

You can upload the barcode image you produced to the ZXing Decoder Online to confirm if it is valid: http://zxing.org/w/decode.jspx There is no intrinsic limit to the length of a Code 128 barcode, and all the characters you have are valid. Having said that, with Code 128A barcodes, having more...

Reading all the files in sequence in MATLAB

matlab,image-processing

From the Matlab forums, the dir command output sorting is not specified, but it seems to be purely alphabetical order (with purely I mean that it does not take into account sorter filenames first). Therefore, you would have to manually sort the names. The following code is taken from this...

Interpolation inside a matrix. Matlab

matlab,matrix

M =[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 0 0 3 0 0...