Odd bounding box coordinates in Matlab - matlab

I'm using regionprops(img,'BoundingBox'); to generate bounding boxes around some objects in an image. The coordinates of the bounding boxes (x, y, width, height) are always by 0.5 off from Integer-values.
Why is that the case?
For me, it is causing two problems:
When using these coordinates for accessing an image array, I get the warning: Warning: Integer operands are required for colon operator when used as index. I can live with that, respectively remove it with floor or ceil, BUT ...
... when these coordinates are close to image borders, they cause
errors since the values 0.5 and 1024.5 don't match with the image
borders 1 and 1024. I get Subscripted assignment dimension mismatch. or Index exceed matrix dimensions., which is plausible.
So can someone explain to me:
Why is it doing this?
How am I supposed to work with it when using the coordinates to crop and replace image regions. I want to replace exactly what was cropped by imcrop and rounding is a bit circumstancial (simply using floor or ceil won't work, I would have to check for the image borders which is not a problem but seems a bit tedious for a rather simple task and certainly questionable whether it is supposed to be used like this...).
Below are some code snippets with which I produced the errors for a 1024x1024 image.
bb_coords = [124.5 979.5 27 45]; % example for bounding box generated by regionprops
subregion = imcrop(img, bb_coords); % works fine with imcrop
% but when I want to use these coordinates for accessing the img array,
% I generally get a warning and in this case an error.
img( bb_coords(2):(bb_coords(2)+bb_coords(4)), ...
bb_coords(1):(bb_coords(1)+bb_coords(3))) = subregion;

Functions in MATLAB that handle image display or processing treat the center of the pixel as lining up with the corresponding coordinate grid points. In other words, for a given dimension of an image, the first pixel center is at 1, the second pixel center is at 2, etc., and the area of each pixel will span +-0.5 on either side of the coordinate. You can see this when you plot an image, turn the axes display on, and zoom in around one of the corners:
img = imread('cameraman.tif'); % Load a sample image
imshow(img); % Display it
set(gca, 'Visible', 'on'); % Make the axes visible
axis([0 5 252 257]); % Zoom in on the bottom left corner
The documentation for regionprops illustrates that the 'BoundingBox' will enclose the entire pixel area, thus leading to a bounding box that appears a full pixel wider (0.5 pixels wider on each side) than the range of center coordinates:
For the 5-by-5 sample image above, the nonzero pixels cover an area that spans the top 4 rows (row coordinates of the pixel centers from 1 to 4) and right 4 columns (column coordinates of the pixel centers from 2 to 5). The bounding box (in green) therefore spans from 0.5 to 4.5 (height of 4) across the rows and 1.5 to 5.5 (width of 4) across the columns.
In short, if you want to use the bounding box values in bb_coords to generate indices into the image, you need to add 0.5 to each corner coordinate and subtract 1 from each width:
ind_coords = bb_coords + [0.5 0.5 -1 -1];
img(ind_coords(2):(ind_coords(2)+ind_coords(4)), ...
ind_coords(1):(ind_coords(1)+ind_coords(3))) = subregion;

Related

Keep subplot in square while having (1,3) tiledlayout [duplicate]

So I have this matrix in MATLAB, 200 deep x 600 wide. It represents an image that is 2cm deep x 6cm wide. How can I plot this image so that it is locked into proper dimensions, i.e. 2cm x 6cm? If I use the image or imagesc commands it stretches it all out of shape and shows it the wrong size. Is there a way to lock it into showing an image where the x and y axes are proportional?
Second question, I need to then set this image into a 640x480 frame (20 pixel black margin on left and right, 280 pixel black margin on bottom). Is there a way to do this?
To keep aspect ratio, you can use axis equal or axis image commands.
Quoting the documentation:
axis equal sets the aspect ratio so that the data units are the same in every direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically according to the range of data units in the x, y, and z directions.
axis image is the same as axis equal except that the plot box fits tightly around the data`
For second question:
third_dimension_size=1; %# for b&w images, use 3 for rgb
framed_image=squeeze(zeros(640,480,third_dimension_size));
framed_image(20:20+600-1,140:140+200-1)= my_600_200_image;
imagesc(framed_image'); axis image;
set(gca,'DataAspectRatio',[1 1 1])
Second question:
new_image = zeros(480,640);
new_image(20:(200+20-1),20:(600+20-1)) = old_image;
As an alternative to the other answers, you might want:
set(gca, 'Units', 'centimeters', 'Position', [1 1 6 2])
Make sure you do this after plotting the image to get the other axis properties correct.
For the second question, take care with the number of colour channels:
new_image = zeros(480,640, size(old_image));
new_image(20:(200+20-1),20:(600+20-1),:) = old_image;

How do I multiply the xticks and yticks with constant and have it displayed in the figure in Matlab 2019?

I've got a picture (a matrix of intensities for every pixel). When plotting this with matlab's imagesc the x-,y-axis are obviously in pixels. I know that 1 pixel corresponds to 0.6250 millimeter in both x- and y-direction.
How can I change only the scale in axis in the figure to show millimeters instead of pixels, i.e how do I multiply the xticks and yticks with 0.6250 and have it displayed in the figure?
I have tried:
new_x = xticks*pixel_spacing(2);
set(gca,'xticklabels', new_x)
but this results in the error
"Unable to use a value of type 'matlab.graphics.axis.Axes' as an index."
imagesc has a syntax where you can specify the scaling of the pixels (see the documentation).
x = [1,size(img,2)] * pixel_spacing;
y = [1,size(img,1)] * pixel_spacing;
imagesc(x,y,img);
(assuming img is your image to display)
The advantage over changing the tick labels is that other things plotted on top of the image will use the same coordinates, as will retrieving mouse cursor location and so forth. This might or might not be relevant, but it’s good to know.
I figured it out.
xticklabels(xticks*pixel_spacing(2))
yticklabels(yticks*pixel_spacing(1))

Matlab: Position of X, Y, width and length to pixel images

I was given some data that I would like to convert to a pixelized image. From what I understood, the original data was plotted by using the function 'rectangle' in Matlab. However, a 2D image is now required.
This data has four columns and ~1000 rows. The first to fourth columns correspond to //
Matrice = [Left corner X, Left corner Y, Width, Height]
So for instance, the first row is [2,3,5,6], meaning that there is a rectangle with lower left corner position of (2,3), width of 5 and height of 6.
I've been trying to find a method to use this data and turn it into an image of any dimensions with any pixel size. Either there is a function out there that I've been missing, or I am missing an easy method. Everything I've tried so far is overly complicated.
This will create filled black rectangles at the specified positions. Experiment with the optional arguments of rectangle to get different visuals.
Assuming your matrix is named A:
figure
for ii = 1:size(A, 1)
rectangle('Position', A[ii, :], 'FaceColor', 'k')
hold on
end
hold off
axis equal % makes the pixels square

Making a sinusoidal curve in an image into a straight line in the output image

I have to make a sinusoidal curve in an image to output an equal straight line in the resulting image.
An example of input sinusoidal image:
What I think is one solution should be:
Placing down the origin of x and y coordinates at the start of the curve, so we will have y=0 at the starting point. Then points on the upper limit will be counted as such that y= y-(delta_y) and for lower limits, y=y+(delta_y)
So to make upper points a straight line, our resulting image will be:
O[x,y-delta_y]= I[x,y];
But how to calculate deltaY for each y on horizontal x axis (it is showing the distance of curve points from horizontal axis)
Another solution could be, to save all information of the curve in a variable and to plot it as a straight line, but how to do it?
Since the curve is blue we can use information from the blue and red channels to extract the curve. Simply subtraction of red channel from blue channel will highlight the curve:
a= imread('kCiTx.jpg');
D=a(:,:,3)-a(:,:,1);
In each column of the image position of the curve is index of the row that it's value is the maximum of that column
[~,im]=max(D);
so we can use row position to shift each column so to create a horizontal line. shifting each column potentially increases size of the image so it is required to increase size of the image by padding the image from top and bottom by the size of the original image so the padded image have the row size of 3 times of the original image and padding value is 255 or white color
pd = padarray(a,[size(a,1) 0 0], 255);
finally for each channel cirshift each column with value of im
for ch = 1:3
for col = 1: size(a,2)
pd(:,col,ch) = circshift(pd(:,col,ch),-im(col));
end
end
So the result will be created with this code:
a= imread('kCiTx.jpg');
D=a(:,:,3)-a(:,:,1);
%position of curve found
[~,im]=max(D);
%pad image
pd = padarray(a,[size(a,1) 0 0], 255);
%shift columns to create a flat curve
for ch = 1:3
for col = 1: size(a,2)
pd(:,col,ch) = circshift(pd(:,col,ch),-im(col));
end
end
figure,imshow(pd,[])
If you are sure you have a sinusoid in your initial image, rather than calculating piece-meal offsets, you may as well estimate the sinusoidal equation:
amplitude = (yMax - yMin)/2
offset = (yMax + yMin)/2
(xValley needs to be the valley immediately after xPeak, alternately you could do peak to peak, but it changes the equation, so this is the more compact version (ie you need to see less of the sinusoid))
frequencyScale = π / (xValley - xPeak)
frequencyShift = xFirstZeroCrossRising
If you are able to calculate all of those, this is then your equation:
y = offset + amplitude * sin(frequencyScale * (x + frequencyShift))
This equation should be all you need to store from one image to be able to shift any other image, it can also be used to generate your offsets to exactly cancel your sinusoid in your image.
All of these terms should be able to be estimated from the image with relatively little difficulty. If you can not figure out how to get any of the terms from the image, let me know and I will explain that one in particular.
If you are looking for some type of distance plot:
Take your first point on the curvy line and copy it into your output image, then measure the distance between that point and the next point on the (curvy) line. Use that distance to offset (from the first point) that next point into the output image only along the x axis. You may want to do it pixel by pixel, or grab clumps of pixels through averaging or jumping (as pixel by pixel will give you some weird digital noise)
If you want to be cleaner, you will want to set up a step size which was sufficiently small to approximately match the maximum sinusoidal curvature without too much error. Then, estimate the distance as stated above to set up bounds and then interpolate each pixel between the start and end point into the image averaging into bins based on approximate position. IE if a pixel from the original image would fall between two bins in the output image, you would split it and add its weighted parts to those two bins.

How to determine Boundary Cut Utilization MATLAB?

Working on 2D Rectangular Nesting. Need to find the utilization percentage of the material. Assuming i have the length, breadth, left-bottom position of each rectangle. What is the best way to determine the Boundary-Cut Utilization?
Objective:- To find the AREA under the RED Line.
Sample images attached to depict what i have done and what i need.
What i have done
what i need
Another Example image of rectangles packed with allowance
If you're interested in determining the total "area" underneath the red line, one suggestion I have is if you have access to the Image Processing Toolbox, simply create a binary image where we draw all of the rectangles on the image at once, fill all of the holes, then to determine the area, just determine the total sum of all of the binary "pixels" in the image. You said you have the (x,y) positions of the bottom-left corner of each rectangle, as well as the width and height of each rectangle. To make this compatible in an image context, the y axis is usually flipped so that the top-left corner of the space is the origin instead of the bottom-left. However, this shouldn't affect our analysis as we are simply reflecting the whole 2D space downwards.
Therefore, I would start with a blank image that is the same size as the grid you are dealing with, then writing a loop that simply sets a rectangular grid of coordinates to true for each rectangle you have. After, use imfill to fill in any of the holes in the image, then calculate the total sum of the pixels to get the area. The definition of a hole in an image processing context is any black pixels that are completely surrounded by white pixels. Therefore, should we have gaps that are surrounded by white pixels, these will get filled in with white.
Therefore, assuming that we have four separate variables of x, y, width and height that are N elements long, where N is the number of rectangles you have, do something like this:
N = numel(x); %// Determine total number of rectangles
rows = 100; cols = 200; %// Define dimensions of grid here
im = false(rows, cols); %// Declare blank image
%// For each rectangle we have...
for idx = 1 : N
%// Set interior of rectangle at location all to true
im(y(idx)+1:y(idx)+height(idx), x(idx)+1:x(idx)+width(idx)) = true;
end
%// Fill in the holes
im_filled = imfill(im, 'holes');
%// Determine total area
ar = sum(im_filled(:));
The indexing in the for loop:
im(y(idx)+1:y(idx)+height(idx), x(idx)+1:x(idx)+width(idx)) = true;
Is a bit tricky to deal with. Bear in mind that I'm assuming that y accesses the rows of the image and x accesses the columns. I'm also assuming that x and y are 0-based, so the origin is at (0,0). Because we access arrays and matrices in MATLAB starting at 1, we need to offset the coordinates by 1. Now, the beginning index for the row starts from y(idx)+1. We end at y(idx) + height(idx) because we technically start at y(idx)+1 but then we need to go up to height(idx) but then we also subtract by 1 as your coordinates begin at 0. Take for example a line with the width of 20, from x = 0 to x = 19. This width is 20, but we draw from 0, up to 20-1 which is 19. Because of the indexing starting at 1 for MATLAB, and the subtraction of 1 due to the 0 indexing, the +1 and -1 cancel, which is why we are just left with y(idx) + height(idx). The same can be said with the x coordinate and the width.
Once we draw all of the rectangles in the image, we use imfill to fill up the holes, then we can sum up the total area by just unrolling the whole image into a single vector and invoking sum. This should (hopefully) get what you need.
Now, if you want to find the area without the filled in holes (I suspect this is what you actually need), then you can skip the imfill step. Simply apply the sum on the im, instead of im_filled, and so:
ar = sum(im(:));
This will sum up all of the "white" pixels in the image, which is effectively the area. I'm not sure what you're actually after, so use one or the other depending on your needs.
Boundary-Cut Area without using Image Processing Toolbox.
The Detailed question description and answer could be found here
This solution is applicable only to Rectangular parts.