OK, we have an image and (0,1,2,3,4,5,6,7) - as images, we need to show image that we have got, next right, the image that got redrawn by numbers (0,1,2,3,4,5,6,7), third on right, is pallete (0,1,2,3,4,5,6,7) and boxes with color.
a) Upload JPEG image. Choose amount rows M and amount columns N for drawing grid. Change image size for required size of grid.
b) Convert image .JPEG in indexed image with 8 colors and show it up as on picture.
c) Prepare image that shows color card.
d) Prepare image that shows grid and color numbers.
m = 80;
n = 60;
im = imresize(imread('1задание.jpg'), [m n] * 10, 'nearest');
small_im = imresize(im, [m n], 'nearest');
[X, map] = rgb2ind(small_im, 8);
big_small_im = im2uint8(ind2rgb(imresize(X, [m n] * 10, 'nearest'), map));
figure;
imshow([im ones(m * 10, 50, 3) * 255 big_small_im ones(m * 10, 50, 3) * 255 ...
generate_cool_map(map, m * 10)]);
digits = [];
for i = 0 : 7
digit = imread([int2str(i) '.png']);
digits = [digits digit];
end
pixel_s = 43;
final_im = im2uint8(ones(m * pixel_s, n * pixel_s, 3) * 255);
for i = 1 : m
for j = 1 : n
final_im((i - 1) * pixel_s + 1 : i * pixel_s, j * pixel_s, :) = zeros(pixel_s, 1, 3);
final_im(j * pixel_s, (j - 1) * pixel_s + 1 : j * pixel_s, :) = zeros(pixel_s, 1, 3);
final_im((i - 1) * pixel_s + 2 : (i - 1) * pixel_s + 2 + 39+4, (j - 1) * pixel_s + 2 : (j - 1) * pixel_s + 2 + 26, :) = digits(:, X(i, j) * 27 + 1 : (X(i, j) + 1) * 27, :);
end
end
figure;
imshow(final_im);
function res = generate_cool_map(map, s)
color_size = floor(s / 8);
m_map = zeros(8, 1, 3);
for i = 1 : 8
m_map(i, 1, :) = map(i, :);
end
res = imresize(m_map, [s, color_size], 'nearest');
res(:, 1:2, :) = zeros(s, 2, 3);
res(:, color_size - 1 : color_size, :) = zeros(s, 2, 3);
for i = 0 : 7
res(i * color_size + 1 : i * color_size + 2, :, :) = zeros(2, color_size, 3);
res(i * color_size + 1 + floor(color_size / 2) : i * color_size + 2 + ...
floor(color_size / 2),1:7,:) = zeros(2,7,3);
res(i * color_size + 1 + floor(color_size / 2) : i * color_size + 2 + ...
floor(color_size / 2), color_size - 6 : color_size, :) = zeros(2,7,3);
end
res(s - 1 : s, :, :) = zeros(2, color_size, 3);
res = [res ones(s, floor(color_size / 3), 3) * 255];
digits = [];
for i = 0 : 7
digit = imread([int2str(i) '.png']);
digits = [digits digit];
end
res = im2uint8(res);
for i = 0 : 7
res(i * color_size + floor(color_size / 3) : i * color_size + ...
floor(color_size / 3) + 39+4, color_size + 6 : color_size + 6 + 26, :) ...
= digits(:, i * 27 + 1 : (i + 1) * 27, :);
end
end
Task how shall look first figure:
I attempted but it seems here is some mistake. :c
Task how shall look second figure:
Figure 1: Resizing and Reducing Unique Colour Count
With the current amount of implementation details here is what I came up with. Resizing the image can be done using the imresize() function and 'nearest' neighbour interpolation. To reduce the number of colours the imapprox() function is used to limit the number of unique colours to 8. Reconstruction of the new image can be done using New_Image_Data (the colour card keys) and New_Colour_Map (the colour card values).
m = 50;
n = 60;
Original_Image = imread('peppers.png');
subplot(1,2,1); imshow(Original_Image);
title("Original Image");
Number_Of_Rows = m;
Number_Of_Columns = n;
%Resizing image%
Resized_Image = imresize(Original_Image,[m n],'nearest');
%Reducing the amount of colours%
Maximum_Intensity = 255;
[Image_Data,Colour_Map] = rgb2ind(Resized_Image,Maximum_Intensity);
[New_Image_Data,New_Colour_Map] = imapprox(Image_Data,Colour_Map,8);
subplot(1,2,2); imshow(New_Image_Data,New_Colour_Map);
title("Resized Image with 8 Colours");
Colour_Bar = colorbar;
set(Colour_Bar,'YTick',(0:7));
Figure 2: Plotting the Grid of Values
%Plotting the grid of card colour values%
Figure_2 = figure(2);
clf;
Figure_2.Position = [0 0 700 700];
x = (0:Number_Of_Rows);
y = (0:Number_Of_Columns);
[X,Y] = meshgrid(x,y);
Z = ones(length(x),length(y)).';
mesh(Y,X,Z);
axis off
hold on
view(0,90);
Image_Data = flip(New_Image_Data);
title("Colour Card Values/Keys");
for Row_Index = 1: Number_Of_Rows
for Column_Index = 1: Number_Of_Columns
text(Column_Index-0.5,Row_Index-0.5,num2str(Image_Data(Row_Index,Column_Index)));
end
end
Ran using MATLAB R2019b
I'm trying to write a matlab program to calculate an integral by means of trapezoidal and simpsons rule. The program for trapezoidal is as follows:
function [int, flag, stats] = trapComp(f, a, b, tol, hMin)
% Initialise variables
h = b - a;
n = 1;
int = h / 2 * (f(a) + f(b));
flag = 1;
if nargout == 3
stats = struct('totalErEst', [], 'totalNrIntervals', [], 'nodesList', []);
end
while h > hMin
h = h / 2;
n = 2 * n;
if h < eps % Check if h is not "zero"
break;
end
% Update the integral with the new nodes
intNew = int / 2;
for j = 1 : 2 : n
intNew = intNew + h * f(a + j * h);
end
% Estimate the error
errorEst = 1 / 3 * (int - intNew);
int = intNew;
if nargout == 3 % Update stats
stats.totalErEst = [stats.totalErEst; abs(errorEst)];
stats.totalNrIntervals = [stats.totalNrIntervals; n / 2];
end
if abs(errorEst) < tol
flag = 0;
break
end
end
end
Now simpsons rule I cant really quite get around. I know its very similar but I cant seem to figure it out.
This is my simpson code:
function [int, flag, stats] = simpComp(f, a, b, tol, hMin)
% Initialise variables
h = b - a;
n = 1;
int = h / 3 * (f(a) + 4 * f((a+b)/2) + f(b));
flag = 1;
if nargout == 3
stats = struct('totalErEst', [], 'totalNrIntervals', [], 'nodesList', []);
end
while h > hMin
h = h / 2;
n = 2 * n;
if h < eps % Check if h is not "zero"
break;
end
% Update the integral with the new nodes
intNew = int / 2;
for j = 1 : 2 : n
intNew = intNew + h * f(a + j * h);
end
% Estimate the error
errorEst = 1 / 3 * (int - intNew);
int = intNew;
if nargout == 3 % Update stats
stats.totalErEst = [stats.totalErEst; abs(errorEst)];
stats.totalNrIntervals = [stats.totalNrIntervals; n / 2];
end
if abs(errorEst) < tol
flag = 0;
break
end
end
end
Using this, however, gives an answer for an integral with a larger error than trapezoidal which i feel it shouldnt.
Any help would be appreciated
I have created a function in matlab which returns an image:
function [BW3] =lineAnalysis( BW1, O)
BW2 = double(BW1 > 0);
BW3 = BW2(2:end, :); % <-- REMOVE 1st LINE (ARTIFACT)!
if O==0; % 1 for left
BW3 = fliplr(BW3); % <-- FLIP IT HERE!
end
BW3_orig = BW3; % <-- SAVE ORIGINAL VERSION
% STEP 1
n = 10; t = 0.9;
c = 0:(n - 1);
j0 = 1;
while mean(mean(BW3(1 + c, j0 + c))) < t
j0 = j0 + 1;
end
% STEP 2
i0 = 1;
while mean(mean(BW3(i0 + c, 1 + c))) < t
i0 = i0 + 1;
end
% STEP 3
a = (1 - j0) / (i0 - 1);
b = j0 - a;
for i = 1:i0
for j = 1:round(a * i + b)
BW3(i, j) = 0;
end
end
% STEP 4
w = 20;
for i = 1:round(i0 - w / a)
for j = max(1, round(a * i + b + 1)):round(a * i + b + w)
BW3(i, j) = 1;
end
end
% PLOT RESULT
[BW3] = size(BW3);
[nr, nc] = size(BW3);
% figure
subplot(122), imagesc(BW3), colormap(gray)
axis equal off, axis([1, nc, 1, nr]), title('Corrected')
This works perfectly.
However I would like to return the result in my main program instead of executing the line
imshow(BW3);
within the function.
I have tried doing this:
[BW3]=lineAnalysis(P, O);
I then tried to show the image by doing
imshow(BW3);
However this doesnt work when I show the image like this. It simply diplays one black image and one white image.
Can anyone tell me how to fix this??
Thanks :)
The problem is near the end of your code:
function [BW3] =lineAnalysis( BW1, O)
%% your calculations here
% PLOT RESULT
[BW3] = size(BW3);
imshow(BW3);
In the line [BW3] = size(BW3); you are replacing the image with a 2 element vector that has the numbers of rows and columns of your image.
In reinforcement learning, a typical example is the windy gridworld
And I face with a new variation of windy gridworld, which additionally has a wall and stochastic wind, I am stuck in these two new things
Figure 1 shows a standard gridworld, with start (S) and goal (G) cells, but with two dierences: there
is a wall the agent can not cross (indicated by the black cells) and there is a crosswind down and to the
left at the right edge of the grid. The available actions in each cell are the king's moves | 8 actions in
total for each cell. If any action would bring you outside the gridworld or collide with the wall, you end
up in the nearest cell (e.g. going northeast in the top left cell will bring you one cell to the right). In the
right region the resultant next cells are shifted down-left by a stochastic \wind", the mean strength of
which varies column by column. The mean strength of the wind is given below each column, in number
of cells shifted down-left.
Due to stochasticity, the wind sometimes varies by 1 from the mean values
given for each column (except if the mean is 0). That is, a third of the time you are shifted down-left
exactly according to the values indicated below the column, a third of the time you are shifted one cell
further down and left that, and another third of the time you are shifted one cell less than the mean.
For example, if you are in the row of the wall and in the middle of the opening and you move up, then
one-third of the time you end up one row west of that cell, one-third of the time you end up two colums
west, one column south of that cell, and one-third of the time you end up at the same column north of
that cell. The wind aects the cell you are in, not the cell you are going to.
Implement the Q-learning algorithm2 in the above problem with = 0:1,
= 0:9 and initial Q(s; a) = 0
for all s; a. Each action generates a reward of rs = 1, except for the actions that lead immediately to
the goal cell (rg = 10). Use the:
-Greedy action selection method with = 0:2.
Greedy action selection method with initial Q(s,a) > 0 and initial Q(s,a) < 0.
my matlab code will work.
My real problem is on the
function nextPos = GiveNextPos(curPos, actionIndex, windpowers, gridCols, gridRows), in which the agent will decide a action, and move to the next step. But there are many factors to influence the next step, such as stochastic wind and wall
so first question is about the stochastic wind, how can I program in matlab to say in 1/3 chance, it is 3, in another 1/3 chance, it is 1...
the second question is about colliding wall?should I firstly calculate the next step for king's walk and wind, and then use this next step value to check if I hit the wall or not???)
function WindyGridWorldQLearning()
fprintf('WindyGridWorldQLearning\n');
gamma = 0.9;
alpha = 0.1;
epsilon = 0.2;
gridcols = 10;
gridrows = 7;
windpowers = [0 0 0 0 1 1 2 2 1 1];
fontsize = 16;
showTitle = 1;
episodeCount = 900;
selectedEpisodes = [900];
isKing = 1;
canHold = 0;
start.row = 7;
start.col = 1;
goal.row = 1;
goal.col = 1;
selectedEpIndex = 1;
actionCount = 8;
% initialize Q with zeros
Q = zeros(gridrows, gridcols, actionCount);
a = 0; % an invalid action
% loop through episodes
for ei = 1:episodeCount,
%disp(sprintf('Running episode %d', ei));
curpos = start;
nextpos = start;
%epsilon or greedy
if(rand > epsilon) % greedy
[qmax, a] = max(Q(curpos.row,curpos.col,:));
else
a = IntRand(1, actionCount);
end
while(PosCmp(curpos, goal) ~= 0)
% take action a, observe r, and nextpos
nextpos = GiveNextPos(curpos, a, windpowers, gridcols, gridrows);
if(PosCmp(nextpos, goal) ~= 0), r = -1; else r = 10; end
% choose a_next from nextpos
[qmax, a_next] = max(Q(nextpos.row,nextpos.col,:));
if(rand <= epsilon) % explore
a_next = IntRand(1, actionCount);
end
% update Q:
curQ = Q(curpos.row, curpos.col, a);
nextQ = qmax; %Q(nextpos.row, nextpos.col, a_next);
Q(curpos.row, curpos.col, a) = curQ + alpha*(r + gamma*nextQ - curQ);
curpos = nextpos; a = a_next;
end % states in each episode
% if the current state of the world is going to be drawn ...
if(selectedEpIndex <= length(selectedEpisodes) && ei == selectedEpisodes(selectedEpIndex))
curpos = start;
rows = []; cols = []; acts = [];
for i = 1:(gridrows + gridcols) * 10,
[qmax, a] = max(Q(curpos.row,curpos.col,:));
nextpos = GiveNextPos(curpos, a, windpowers, gridcols, gridrows);
rows = [rows curpos.row];
cols = [cols curpos.col];
acts = [acts a];
if(PosCmp(nextpos, goal) == 0), break; end
curpos = nextpos;
end % states in each episode
%figure;
figure('Name',sprintf('Episode: %d', ei), 'NumberTitle','off');
DrawWindyEpisodeState(rows, cols, acts, start.row, start.col, goal.row, goal.col, windpowers, gridrows, gridcols, fontsize);
if(showTitle == 1),
title(sprintf('Windy grid-world SARSA - episode %d - (\\epsilon: %3.3f), (\\alpha = %3.4f), (\\gamma = %1.1f)', ei, epsilon, alpha, gamma));
end
selectedEpIndex = selectedEpIndex + 1;
end
end % episodes loop
function c = PosCmp(pos1, pos2)
c = pos1.row - pos2.row;
if(c == 0)
c = c + pos1.col - pos2.col;
end
function nextPos = GiveNextPos(curPos, actionIndex, windpowers, gridCols, gridRows)
nextPos = curPos;
switch actionIndex
case 1 % east
nextPos.col = curPos.col + 1;
case 2 % south
nextPos.row = curPos.row + 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.row = curPos.row; end
case 3 % west
nextPos.col = curPos.col - 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.col = curPos.col; end
case 4 % north
nextPos.row = curPos.row - 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.row = curPos.row; end
case 5 % northeast
nextPos.col = curPos.col + 1;
nextPos.row = curPos.row - 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.row = curPos.row; end
case 6 % southeast
nextPos.col = curPos.col + 1;
nextPos.row = curPos.row + 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.row = curPos.row; end
case 7 % southwest
nextPos.col = curPos.col - 1;
nextPos.row = curPos.row + 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.row = curPos.row; end
case 8 % northwest
nextPos.col = curPos.col - 1;
nextPos.row = curPos.row - 1;
if(nextPos.row ==4 && nextPos.col <= 4 ) nextPos.row = curPos.row; end
case 9 % hold
nextPos = curPos;
otherwise
disp(sprintf('invalid action index: %d', actionIndex))
end
if(curPos.col > 4)
nextPos.row = nextPos.row - windpowers(nextPos.col);
nextPos.col = nextPos.col - windpowers(nextPos.col);
end
if(nextPos.col <= 0), nextPos.col = 1; end
if(nextPos.col > gridCols), nextPos.col = gridCols; end
if(nextPos.row <= 0), nextPos.row = 1; end
if(nextPos.row > gridRows), nextPos.row = gridRows; end
function n = IntRand(lowerBound, upperBound)
n = floor((upperBound - lowerBound) * rand + lowerBound);
function DrawWindyEpisodeState(rows, cols, acts, SRow, SCol, GRow, GCol, windpowers, gridrows, gridcols, fontsize)
DrawGrid(gridrows, gridcols);
DrawTextOnCell('S', 0, SRow, SCol, gridrows, gridcols, fontsize);
DrawTextOnCell('G', 0, GRow, GCol, gridrows, gridcols, fontsize);
for i=1:length(rows),
DrawActionOnCell(acts(i), rows(i), cols(i), gridrows, gridcols, fontsize);
end
for i=1:gridcols,
[xc, yc] = FindColBaseCenter(i, gridrows, gridcols);
text(xc, yc, sprintf('%d',windpowers(i)), 'FontSize', fontsize, 'Rotation', 0);
end
function DrawEpisodeState(rows, cols, acts, SRow, SCol, GRow, GCol, gridrows, gridcols, fontsize)
DrawGrid(gridrows, gridcols);
DrawTextOnCell('S', 0, SRow, SCol, gridrows, gridcols, fontsize);
DrawTextOnCell('G', 0, GRow, GCol, gridrows, gridcols, fontsize);
for i=1:length(rows),
DrawActionOnCell(acts(i), rows(i), cols(i), gridrows, gridcols, fontsize);
end
function DrawGrid(gridrows, gridcols)
xsp = 1 / (gridcols + 2);
ysp = 1 / (gridrows + 2);
x = zeros(1, 2*(gridcols + 1));
y = zeros(1, 2*(gridcols + 1));
i = 1;
for xi = xsp:xsp:1 - xsp,
x(2*i - 1) = xi; x(2*i) = xi;
if(mod(i , 2) == 0)
y(2*i - 1) = ysp;y(2*i) = 1-ysp;
else
y(2*i - 1) = 1 - ysp;y(2*i) = ysp;
end
i = i + 1;
end
x2 = zeros(1, 2*(gridrows + 1));
y2 = zeros(1, 2*(gridrows + 1));
i = 1;
for yi = ysp:ysp:1 - ysp,
y2(2*i - 1) = yi; y2(2*i) = yi;
if(mod(i , 2) == 0)
x2(2*i - 1) = xsp;x2(2*i) = 1-xsp;
else
x2(2*i - 1) = 1 - xsp;x2(2*i) = xsp;
end
i = i + 1;
end
plot(x, y, '-');
hold on
plot(x2, y2, '-');
axis([0 1 0 1]);
axis off
set(gcf, 'color', 'white');
function DrawTextOnCell(theText, rotation, row, col, gridrows, gridcols, fontsize)
[xc, yc] = FindCellCenter(row, col, gridrows, gridcols);
text(xc, yc, theText, 'FontSize', fontsize, 'Rotation', rotation);
function DrawActionOnCell(actionIndex, row, col, gridrows, gridcols, fontsize)
rotation = 0;
textToDraw = 'o';
switch actionIndex
case 1 % east
textToDraw = '\rightarrow';
rotation = 0;
case 2 % south
textToDraw = '\downarrow';
rotation = 0;
case 3 % west
textToDraw = '\leftarrow';
rotation = 0;
case 4 % north
textToDraw = '\uparrow';
rotation = 0;
case 5 % northeast
textToDraw = '\rightarrow';
rotation = 45;
case 6 % southeast
textToDraw = '\downarrow';
rotation = 45;
case 7 % southwest
textToDraw = '\leftarrow';
rotation = 45;
case 8 % northwest
textToDraw = '\uparrow';
rotation = 45;
otherwise
disp(sprintf('invalid action index: %d', actionIndex))
end
DrawTextOnCell(textToDraw, rotation, row, col, gridrows, gridcols, fontsize);
function [x,y] = FindCellCenter(row, col, gridrows, gridcols)
xsp = 1 / (gridcols + 2);
ysp = 1 / (gridrows + 2);
x = ((2*col + 1) / 2) * xsp;
y = 1 - (((2*row + 1) / 2) * ysp);
x = x - xsp/5;
function [x,y] = FindColBaseCenter(col, gridrows, gridcols)
row = gridrows + 1;
xsp = 1 / (gridcols + 2);
ysp = 1 / (gridrows + 2);
x = ((2*col + 1) / 2) * xsp;
y = 1 - (((2*row + 1) / 2) * ysp);
x = x - xsp/5;
For the wind just generate a random number n, say between 0 and 1. If you want 3 different behaviors each with a 1/3 chance, just have conditions for n < .33 , .33 < n < .66 ... etc.
I don't quite understand what you're saying with the wall, but you should check the action the agent will take and the effect the wind will have on it and then see if this results in you hitting a wall. If so take the appropriate action.
I'm trying to make a B-Spline Function
first i set the variables and made the Knot vector
# cmpp.m
% Set variables
k = 3; % (8 mod 2 + 2 + 1)
p = k - 1; % Order = 2
n = 2*k - 1; % Control points = 5
l = n + p + 1; % Vector size n + p + 1 = 8
% Create the Knot vector
% Kv = [0 0 0 1 2 3 3 3] size = 8
knoten = 0; % set all knots to 0
Kv = [];
for j=1:1:l
Kv = [ Kv 0 ];
end
for i=1:1:l
if (i > n)
if (i <= n)
Kv(i) = knoten + 1;
knoten = knoten + 1;
else
Kv(i) = knoten;
end
else
Kv(i) = knoten;
end
end
then i worte a function to create the basic function
# f.m
function N = f(N,t,i,k,u,x,s)
if (u < x)
N(i,k) = ((((u-t(i)).*f(t,i,k-1,u+s,x,s)) / (t(i+k-1) - t(i))) + (((t(i+k)-u).*f(t,i+1,k-1,u+s,x,s)) / (t(i+k) - t(i+1))));
if ((u >= t(i)) && (u < t(i+1)))
N(i,1) = 1;
else
N(i,1) = 0;
end
end
end
and called it in cmpp.m
# cmpp.m
...
...
...
N = zeros(l,k);
x = (n+1) - (k-1);
s = 1;
N = [N f(N,Kv,1,k,0,x,s)];
but i get always this error in Matlab
>> cmpp
Subscripted assignment dimension mismatch.
Error in f (line 3)
N(i,k) = ((((u-t(i)).*f(t,i,k-1,u+s,x,s)) / (t(i+k-1) - t(i))) +
(((t(i+k)-u).*f(t,i+1,k-1,u+s,x,s)) / (t(i+k) - t(i+1))));
Error in cmpp (line 32)
N = [N f(N,Kv,1,k,0,x,s)]