I am developing an IA algorithm for a robot that needs to follow a line. The floor will be black, with a white line and there will be different marks that determine different types of "obstacles". I'm using a sensor that gives me an array of 8 measurements of the floor, as seen on the Figure 1 that give me an array of 8 measurements from 0 to 1000, where 0 there is no white and 1000 is totally white. In the examples bellow is a measurement of a white line in the middle of the sensor array and other cases.
int array[] = {50, 24, 9, 960, 1000, 150, 50, 45} // white line in the middle
int array2[] = {50, 24, 9, 960, 1000, 150, 50, 960} // white line in the middle and a square box on the right
int array3[] = {1000, 24, 9, 960, 1000, 150, 50, 40} // white line in the middle and a square box on the left
int array4[] = {1000, 980, 950, 0, 10, 980, 1000, 960} // black square box in the middle
Witch algorithms I could use to detect the patterns on the images below given this array of measurements? I do not want to use several "hardcoded" conditionals as templates, as I think it will not scale well. Im thinking on implementing a "peak counter" algorithm, but I do not know if it will work robust enough.
On the Figures we can see the different cases, the case I want to detect are the ones with the red circle.
Thanks!
How about doing something simple like treating each measurement like an N-dimensional vector. In your case N=8. Then, all you measurements are contained in a hypercube with sides up to length 1000. For N=8 there will be 256 corners. For each of your cases of interest, associate the hypercube corners that best match up to it. Note, some corners may not get associated. Then, for each measurement find its nearest associated hypercube corner. This tells you which case it is. You can mitigate errors by implementing some checks. For example, if the measurement is close to multiple corners (within some uncertainty threshold) then you label the measurement as being ambiguous and skip it.
It's easier to see this for the case of 3 measurements. The 8 corners of the cube could represent
[0,0,0] = no white
[0,0,1] = white on right
[0,1,0] = white in middle
[0,1,1] = white in middle and right
[1,0,0] = white on left
[1,0,1] = white on left and right
[1,1,0] = white on left and middle
[1,1,1] = all white
The case shown below is an ambiguous measurement in the middle.
(source: ctralie.com)
Related
I have an image that I import into Octave 5.2, and I would like to create an outline all the way around the image array using RGB values.
I'm having trouble inserting the RGB values back into the array correctly, inserting / generating the two rows at top, two columns on the left, two columns on the right, and two rows on the bottom all the way around the image / converted double array.
Example of original image:
Example of the image I'm trying to get when done:
My logic was:
To convert the image to a double array so I can do math / insert the RGB values where I wanted them.
Insert the RGB values into the left, right, top, bottom of the array.
Convert the double array back to uint8 to export / view it as image.
My code so far:
pkg load image
img_fn=('https://i.imgur.com/KKxJaOy.png'); %original image
f=imread(img_fn);
[im_r im_c]=size(f);
size_min=min(im_r,im_c); %get minum size from row and col
f_double=double(f); %need to convert to double to do math functions on it
outline_left_of_box=repmat(255,[rows(f_double),2]); %Create left line array of outline red box
f_double_tmp_red(:,:,1)=[outline_left_of_box,f_double];%Create left line of outline red box
red_outline_right_of_box=repmat(255,[rows(f_double),2]); %Create right line array of outline red box
red_outline_top_of_box=repmat(255,[2,columns(f_double)]); %Create top line array of outline red box
red_outline_bottom_of_box=repmat(255,[2,columns(f_double)]); %Create bottom line array of outline red box
%convert back to image
red_outline_img=uint8(f_double);
imshow(red_outline_img); %used to show image in octave plot window
Please note: I'm converting the image array into a double because calculations will be done on the array to get the desired color box around the image, but I'm just trying to get the inserting RGB values into the array issue fixed first.
Maybe it's easier to simply paste the inner part of the input image onto some "background" image with the desired border color, like so:
pkg load image
% Read image, get dimensions, convert to double
f = imread('https://i.imgur.com/KKxJaOy.png');
[im_ro, im_co, im_ch] = size(f);
f_double = double(f);
% Set up width and color of border
bw = 2;
color = ones(1, 1, im_ch);
color(1, 1, :) = [255, 0, 0];
% Create image of same size as input with solid color, and paste inner part of input
red_outline_img = ones(im_ro, im_co, im_ch) .* color;
red_outline_img(bw+1:end-bw, bw+1:end-bw, :) = f_double(bw+1:end-bw, bw+1:end-bw, :);
red_outline_img = uint8(red_outline_img);
imshow(red_outline_img);
That'd be the output:
Another thing you could try is plot the lines as you suggest, which can be done very efficiently with some clever use of xlim/ylim, and then print the whole thing as an -RGBImage to get it back in image form.
The only caveat here though is that you will need to play with the formatting options to get what you're really after (e.g. in case you want higher or lower resolution), since you really are printing what's on your screen at this point.
E.g.
L = imread('leaf.png');
imshow(L)
hold on
plot( [xlim, fliplr(xlim);xlim, xlim], [ylim, ylim;fliplr(ylim), ylim], 'r', 'linewidth', 2 )
hold off
set( gca, 'position', [0, 0, 1, 1] );
set( gcf, 'paperposition', [0, 0, 1, 1] );
R = print( '-RGBImage' );
close
imshow(R); set( gcf, 'color', 'k'); axis off
I am new to the concept of multi-dimensional array and I am trying to apply it to the following image that I have:
What I would like to do is to create a 5D array as follow [number of boxes in a row, number of boxes in a column, size of each box in x, size of each box in y, RGB] in this example it would be [8, 8, 200, 200, 3].
I have written the following code to grab the pixels of the top left box (the red one) (just to test it):
Image = imread('Grid.jpg');
img = zeros(8, 8, 200, 200, 3)
img(1, 1, 1:200, 1:200, :) = Image(1:200, 1:200, :);
imshow(squeeze(img(1,1,:,:,:)))
When I run the code I only get a yellow line.
Could somebody please point out what am I doing wrong and why I am getting the result I am getting now?
I'm doing an Artificial Intelligence track at HackerRank and this is the first time I do this kind of programs.
On the first program, https://www.hackerrank.com/challenges/saveprincess/problem, I have to do the following:
Princess Peach is trapped in one of the four corners of a square grid.
You are in the center of the grid and can move one step at a time in
any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the
size of the grid. This is followed by an NxN grid. Each cell is
denoted by '-' (ascii value: 45). The bot position is denoted by 'm'
and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go.
The moves must be separated by '\n', a newline. The valid moves are
LEFT or RIGHT or UP or DOWN.
What should I do in these kind of problems?
Move to one corner and check if the princess is there, and it is not, move to another corner?
Here the goal is to do it in as few steps as possible but I think that will only happen if I'm lucky and I find the princess in the first corner to which I move.
I have thought that I could check if the princess is the corner I'm moving to before move to it, but I don't know if it is allowed in this problem.
Read the description of the input format (emphasis mine):
This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
You do not have to actually go to each corner to see whether the princess is there, you already know where she is! Just determine the difference in position of the cells containing the bot m and the princess p and print the accordant movements. E.g., if the difference is 2 in x and -1 and y direction, you might go right right up.
What a boring problem... Seriously.
Load in the input data, starting with the grid size.
Accept lines of input corresponding to the grid size.
Since you know that the grid is a square, check the corners and move diagonally corresponding to what corner the princess is in.
Solution in 7 lines of python:
gridsize = int(input('Enter number of rows: '))
grid = [ input('Enter row: ') for r in range(gridsize) ]
move_dist = (gridsize-1)//2
if grid[ 0][ 0] == 'p': print('\n'.join([ 'UP\nLEFT'] * move_dist))
elif grid[ 0][-1] == 'p': print('\n'.join([ 'UP\nRIGHT'] * move_dist))
elif grid[-1][ 0] == 'p': print('\n'.join([ 'DOWN\nLEFT'] * move_dist))
elif grid[-1][-1] == 'p': print('\n'.join(['DOWN\nRIGHT'] * move_dist))
I am trying to generate a graph that should look similar to:
My arrays are:
Array4:[Nan;Nan;.......;20;21;22;23;24;..........60]
Array3:[[Nan;Nan;.......;20;21;22;23;24;..........60]
Array2:[0;1;2;3;4;5;6;Nan;Nan;Nan;Nan;17;18;.....60]
Array1:[0;1;2;3;4;5;6;Nan;Nan;Nan;Nan;17;18;.....60]
I cannot find the right way to group my arrays in order to plot them in the way shown on the above graph.
I tried using the following function explained in: http://uk.mathworks.com/help/matlab/ref/barh.html
barh(1:numel(x),y,'hist')
where y=[Array1,Array2;Array3,Array4] and x={'1m';'2m';'3m';......'60m'}
but it does not work.
Why Your Current Approach Isn't Working
Your intuition makes sense to me, but the barh function you are using doesn't work the way you think it does. Specifically, you are interpreting the meaning of the x and y inputs to that function incorrectly. Those are inputs are constant values, not entire axes. The first y input refers to the end-point of the bar that stretches horizontally from x = 0 and the first x input refers to location on the y-axis of the horizontal bar. To illustrate what I mean, I've provided the below horizontal bar graph:
You can find this same picture in the official documentation of the MATLAB barh function. The code used to generate this bar graph is also given in the documentation, shown below:
x = 1900:10:2000;
y = [57,91,105,123,131,150,...
170,203,226.5,249,281.4];
figure;
barh(x, y);
The individual elements of the x array, rather confusingly, show up on the y-axis as the starting locations of each bar. The corresponding elements of the y array are the lengths of each bar. This is the reason that the arrays must be the same length, and this illustrates that they are not specifications of the x and y axes as one might intuitively believe.
An Approach To Solve Your Problem
First things first, the easiest approach is to do this manually with the plot function and a set of lines that represent floating bars. Consult the official documentation for the plot function if you'd like to plot the lines with some sort of color coordination in mind - the code I present (modified version of this answer on StackOverflow) just switches the color of the floating bars between red and blue. I tried to comment the code so that the purpose of each variable is clear. The code I present below matches the floating bar graph that you want to be plotted, if you are alright with replacing thick floating bars with 2D lines floating on a plot.
I used the data that you gave in your question to specify the floating horizontal bars that this script would output - a screenshot is shown below the code. Array1 & Array2:[0;1;2;3;4;5;6;Nan;Nan;Nan;Nan;17;18;.....60], these arrays go from 0 to 6 (length = 6) and 17 to 60 (length = 60 - 17 = 43). Because there is a "discontinuity" of sorts from 7 to 16, I have to define two floating bars for each array. Hence, the first four values in my length array are [6, 6, 43, 43]. Where the first 6 and the first 43 correspond to Array1 and the second 6 and the second 43 correspond to Array2. Recognizing this "discontinuity", the starting point of the first floating bar for Array1 and Array2 is x = 0 and the starting point of the second floating bar for Array1 and Array2 is x = 7. Putting that all together, you arrive at the x-coordinates for the first four points in the floating_bars array, [0 0; 0 1.5; 17 0; 17 1.5]. The y-coordinates in this array only serve to distinguish Array1, Array2, and so on from each other.
Code:
floating_bars=[0 0; 0 1.5; 17 0; 17 1.5; 20 6; 20 7.5]; % Each row is the [x,y] coordinate pair of the starting point for the floating bar
L=[6, 6, 43, 43, 40, 40]; % Length of each consecutive bar
thickness = 0.75;
figure;
for i=1:size(floating_bars,1)
curr_thickness = 0;
% It is aesthetically pleasing to have thicker bars, this makes the plot look for like the grouped horizontal bar graph that you want
while (curr_thickness < thickness)
% Each bar group has two bars; set the first to be red, the second to be blue (i.e., even index means red bar, odd index means blue bar)
if mod(i, 2)
plot([floating_bars(i,1), floating_bars(i,1)+L(i)], [floating_bars(i,2) + curr_thickness, floating_bars(i,2) + curr_thickness], 'r')
else
plot([floating_bars(i,1), floating_bars(i,1)+L(i)], [floating_bars(i,2) + curr_thickness, floating_bars(i,2) + curr_thickness], 'b')
end
curr_thickness = curr_thickness + 0.05;
hold on % Make sure that plotting the current floating bar does not overwrite previous float bars that have already been plotted
end
end
ylim([ -10 30]) % Set the y-axis limits so that you can see more clearly the floating bars that would have rested right on the x-axis (y = 0)
Output:
How Do I Do This With the barh Function?
The short answer is that you'd have to modify the function manually. Someone has already done this with one of the bar graph plotting functions provided by MATLAB, bar3. The logic implemented in this modified bar3 function can be re-applied for your purposes if you read their barNew.m function and tweak it a bit. If you'd like a pointer as to where to start, I'd suggest looking at how they specify z-axis minimum and maximums for their floating bars on the plot, and apply that same logic to specify x-axis minimum and maximums for your floating bars in your 2D case.
I hope this helps, happy coding! :)
I explain here my approach to generate these type of graphs. Not sure if it is the best but it works and there is no need to do anything manually. I came up with this solution based on the following Vladislav Martin's explained fact: "The y-coordinates in this array only serve to distinguish Array1, Array2, and so on from each other".
My original arrays are:
Array4=[Nan....;20;21;22;23;24;..........60]
Array3=[Nan....;20;21;22;23;24;..........60]
Array2=[0;1;2;3;4;5;6;Nan;Nan;Nan;Nan;17;18;.....60]
Array1=[0;1;2;3;4;5;6;Nan;Nan;Nan;Nan;17;18;.....60]
x={'0m';'1m';'2m';'3m';'4m';....'60m'}
The values contained in these arrays make reference to the x-axis on the graph. In order to make the things more simple and to avoid having to code a function to determine the length for each discontinuity in the arrays, I replace these values for y-axis position values. Basically I give to Array1 y-axis position values of 0 and to Array2 0+0.02=0.02. To Array3 I give y-axis position values of 0.5 and to Array4 0.5+0.02=0.52. In this way, Array2 will be plotted on the graph closer to Array1 which will form the first group and Array4 closer to Array3 which will form the second group.
Datatable=table(Array1,Array2,Array3,Array4);
cont1=0;
cont2=0.02;
for col=1:2:size(Datatable,2)
col2=col+1;
for row=1:size(Datatable,1)
if isnan(Datatable{row,col})==0 % For first array in the group: If the value is not nan, I replace it for the corresponnding cont1 value
Datatable{row,col}=cont1;
end
if isnan(Datatable{row,col2})==0 % For second array in the group: If the value is not nan, I replace it for the corresponnding cont2 value
Datatable{row,col2}=cont2;
end
end
cont1=cont1+0.5;
cont2=cont2+0.5;
end
The result of the above code will be a table like the following:
And now I plot the Arrays using 2D floating lines:
figure
for array=1:2:size(Datatable,2)
FirstPair=cell2mat(table2cell(Datatable(:,array)));
SecondPair=cell2mat(table2cell(Datatable(:,array+1)));
hold on
plot(1:numel(x),FirstPair,'r','Linewidth',6)
plot(1:numel(x),SecondPair,'b','Linewidth',6)
hold off
end
set(gca,'xticklabel',x)
And this will generate the following graph:
I'm trying to represent a rectangular area which crosses 180 degrees longitude. For more background see In PostGIS a polygon bigger than half the world is treated as it's opposite
Here's my test case:
from django.contrib.gis.geos import Polygon, MultiPolygon
from my_project.my_app.models import Photo
a = Polygon.from_bbox((30, -80, 180, 80)) # the part to the east of 180
b = Polygon.from_bbox((-180, -80, -160, 80)) # a part to the west of 180
c = Polygon.from_bbox((-180, -80, -100, 80)) # a larger part to the west of 180
ok = MultiPolygon(a,b)
ok2 = MultiPolygon(c)
boom = MultiPolygon(a,c)
# This works
Photo.objects.filter(location__coveredby=ok)[:1]
# This also works so c is ok
Photo.objects.filter(location__coveredby=ok2)[:1]
# This gives "BOOM! Could not generate outside point!"
Photo.objects.filter(location__coveredby=boom)[:1]
# splitting c doesn't help
c1 = Polygon.from_bbox((-180, -80, -140, 80))
c2 = Polygon.from_bbox((-140, -80, -100, 80))
test = MultiPolygon(a,c1,c2)
Photo.objects.filter(location__coveredby=test)[:1]
# BOOM! Could not generate outside point!
By changing the numbers I can make this error come and go.
(-180, -80, x, 80) works where x <= -140 for example. For every number there is a threshold like this but I can't find a pattern. For boxes with the same area, some will work and others not. For boxes with the same width some will work and others not.
I can look at the SQL being generated but the areas are represented in binary (EWKB) and I'm not sure how to read it.
Can anyone explain this?
After asking this question I found out about gis.stackexchange.com, so I asked there too. With the help of the good folks there I found out what the problem is (I think) and a solution.
See:
https://gis.stackexchange.com/questions/9217/postgis-certain-multipolygons-cause-boom-could-not-generate-outside-point/9257#9257