Creating a checkerboard using Ruby and "\n" not disappearing - ruby

I feel as if I am close to a solution and have been tinkering around with this as a newb for some time. Why, for some reason, are my "\n"'s not disappearing when outputted for "next line" and the output has unneeded white space?
Task: Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board.
The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colors ensure the board doesn't look reversed on code wars' dark background). It should return a string of the board with a space in between each square and taking into account new lines.
An even number should return a board that begins with a dark square. An odd number should return a board that begins with a light square.
The input is expected to be a whole number that's at least two, and returns false otherwise (Nothing in Haskell).
I am close, and here is what I have so far:
def checkered_board(dimension)
black = "\u25A1 "
white = "\u25A0 "
checkboard = nil
checker_array = []
if dimension < 2 or dimension.is_a? String
return false
else
count = dimension
while count <= dimension && count > 0
if count % 2 == 0
checkboard = ("\u25A1 \u25A0" + "\n")
checker_array << checkboard
count -= 1
else
checkboard = ("\u25A0 \u25A1" + "\n")
checker_array << checkboard
count -= 1
end
end
end
checkboard = checker_array.join(" ")
p checkboard
end
Here is the TDD specs:
Test.assert_equals(checkered_board(0), false)
Test.assert_equals(checkered_board(2), "\u25A1 \u25A0\n\u25A0 \u25A1")
Note: Hidden specs demonstrate that it should respond with false if dimension is not an integer. .is_a? String and .is_a? Integer is not working for me too.
Output appears like so, and is not appearing even:
□ ■
■ □
Thanks for any and all help :).

Try changing:
if dimension < 2 or dimension.is_a? String
to
if !dimension.is_a?(Integer) || dimension < 2
The left most test will be done first. At the moment, if dimension is a String, it is first compared with 2 - which will raise an error - before it is tested as to whether it is a String. You need to check the type of object before you compare it with another object.
Also, I think the check should be whether dimension is not an Integer, rather than whether it is a String. For example, in your original code, what would happen if dimension was an Array?

The join method will concatenate the elements with a space character inserted between them. So this line from the program:
checkboard = checker_array.join(" ")
will result in this string:
"\u25A1 \u25A0\n \u25A0 \u25A1"
Omitting the argument to join should produce the expected output, ie.:
checkboard = checker_array.join
Refer to the documentation on the Array join method.

Related

Writing a function that returns true if given string has exactly 6 characters

I am trying to write a function that returns true or false if a given string has exactly 6 consecutive characters with the same value. If the string has more or less than 6, it will return false:
I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations
Two example runs are shown below:
Enter a string: 367777776
True
Enter a string: 3677777777776
False
Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')
I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I
def consecutive(x):
storage= ' '
acc=0
count=0
for s in x:
storage+= str(ord(s)) + ' '
acc+=ord(s)
if acc == acc:
count+=1
for s in x-1:
return count
My intention is to compare the previous character's ASCII code to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.
Can anyone assist me?
That's a pretty good start!
A few comments:
Variables storage and acc play the same role, and are a little more complicated than they have to be. All you want to know when you arrive at character s is whether or not s is identical to the previous character. So, you only need to store the previously seen character.
Condition acc == acc is always going to be True. I think you meant acc == s?
When you encounter an identical character, you correctly increase the count with count += 1. However, when we change characters, you should reset the count.
With these comments in mind, I fixed your code, then blanked out a few parts for you to fill. I've also renamed storage and acc to previous_char which I think is more explicit.
def has_6_consecutive(x):
previous_char = None
count = 0
for s in x:
if s == previous_char:
???
elif count == 6:
???
else:
???
previous_char = ???
???
You could use recursion. Loop over all the characters and for each one check to see of the next 6 are identical. If so, return true. If you get to the end of the array (or even within 6 characters of the end), return false.
For more info on recursion, check this out: https://www.programiz.com/python-programming/recursion
would something like this be allowed?
def consecF(n):
consec = 1
prev = n[0]
for i in n:
if i==prev:
consec+=1
else:
consec=1
if consec == 6:
return True
prev = i
return False
n = "12111123333221"
print(consecF(n))
You can try a two pointer approach, where the left pointer is fixed at the first instance of some digit and the right one is shifted as long as the digit is seen.
def consecutive(x):
left = 0
while left != len(x):
right = left
while right < len(x) and x[right] == x[left]:
right += 1
length = (right - 1) - left + 1 # from left to right - 1 inclusive, x[left] repeated
if length == 6: # found desired length
return True
left = right
return False # no segment found
tests = [
'3677777777776',
'367777776'
]
for test in tests:
print(f"{test}: {consecutive(test)}")
Output
3677777777776: False
367777776: True
You should store the current sequence of repeated chars.
def consecutive(x):
sequencechar = ' '
repetitions = 0
for ch in x:
if ch != sequencechar:
if repetitions == 6:
break
sequencechar = ch
repetitions = 1
else:
repetitions += 1
return repetitions == 6
If I could, I would not have given the entire solution, but this still is a simple problem. However one has to take care of some points.
As you see the current sequence is stored, and when the sequence is ended and a new starts, on having found a correct sequence it breaks out of the for loop.
Also after the for loop ends normally, the last sequence is checked (which was not done in the loop).

Parallel loops and image processing in matlab

I am going to implement a salient object detection method based on a simple linear feedback control system (LFCS). The control system model is represented as in the following equation:
I've come up with the following program codes but the result would not be what should be. Specifically, the output should be something like the following image:
But the code produces this output:
The codes are as follows.
%Calculation of euclidian distance between adjacent superpixels stores in variable of Euc
A = imread('aa.jpg');
[rows, columns, cnumberOfColorChannels] = size(A);
[L,N] = superpixels(A,400);
%% Determination of adjacent superpixels
glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset',[0,1;1,0]); %Create gray-level co-occurrence matrix from image
glcms = sum(glcms,3); % add together the two matrices
glcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric
glcms(1:N+1:end) = 0; % set the diagonal to zero, we don't want to see "1 is neighbor of 1"
idx = label2idx(L); % Convert label matrix to cell array of linear indices
numRows = size(A,1);
numCols = size(A,2);
%%Mean color in Lab color space for each channel
data = zeros(N,3);
for labelVal = 1:N
redIdx = idx{labelVal};
greenIdx = idx{labelVal}+numRows*numCols;
blueIdx = idx{labelVal}+2*numRows*numCols;
data(labelVal,1) = mean(A(redIdx));
data(labelVal,2) = mean(A(greenIdx));
data(labelVal,3) = mean(A(blueIdx));
end
Euc=zeros(N);
%%Calculation of euclidian distance between adjacent superpixels stores in Euc
for a=1:N
for b=1:N
if glcms(a,b)~=0
Euc(a,b)=sqrt(((data(a,1)-data(b,1))^2)+((data(a,2)-data(b,2))^2)+((data(a,3)-data(b,3))^2));
end
end
end
%%Creation of Connectivity matrix "W" between adjacent superpixels
W=zeros(N);
W_num=zeros(N);
W_den=zeros(N);
OMG1=0.1;
for c=1:N
for d=1:N
if(Euc(c,d)~=0)
W_num(c,d)=exp(-OMG1*(Euc(c,d)));
W_den(c,c)=W_num(c,d)+W_den(c,c); %
end
end
end
%Connectivity matrix W between adjacent superpixels
for e=1:N
for f=1:N
if(Euc(e,f)~=0)
W(e,f)=(W_num(e,f))/(W_den(e,e));
end
end
end
%%calculation of geodesic distance between nonadjacent superpixels stores in variable "s_star_temp"
s_star_temp=zeros(N); %temporary variable for geodesic distance measurement
W_sparse=zeros(N);
W_sparse=sparse(W);
for g=1:N
for h=1:N
if W(g,h)==0 & g~=h;
s_star_temp(g,h)=graphshortestpath(W_sparse,g,h,'directed',false);
end
end
end
%%Calculation of connectivity matrix for nonadjacent superpixels stores in "S_star" variable"
S_star=zeros(N);
OMG2=8;
for i=1:N
for j=1:N
if s_star_temp(i,j)~=0
S_star(i,j)=exp(-OMG2*s_star_temp(i,j));
end
end
end
%%Calculation of connectivity matrix "S" for measuring connectivity between all superpixels
S=zeros(N);
S=S_star+W;
%% Defining non-isolation level for connectivity matrix "W"
g_star=zeros(N);
for k=1:N
g_star(k,k)=max(W(k,:));
end
%%Limiting the range of g_star and calculation of isolation cue matrix "G"
alpha1=0.15;
alpha2=0.85;
G=zeros(N);
for l=1:N
G(l,l)=alpha1*(g_star(l,l)- min(g_star(:)))/(max(g_star(:))- min(g_star(:)))+(alpha2 - alpha1);
end
%%Determining the supperpixels that surrounding the image boundary
lr = L([1,end],:);
tb = L(:,[1,end]);
labels = unique([lr(:);tb(:)]);
%% Calculation of background likelihood for each superpixels stores in"BgLike"
sum_temp=0;
temp=zeros(1,N);
BgLike=zeros(N,1);
BgLike_num=zeros(N);
BgLike_den=zeros(N);
for m=1:N
for n=1:N
if ismember(n,labels)==1
BgLike_num(m,m)=S(m,n)+ BgLike_num(m,m);
end
end
end
for o=1:N
for p=1:N
for q=1:N
if W(p,q)~=0
temp(q)=S(o,p)-S(o,q);
end
end
sum_temp=max(temp)+sum_temp;
temp=0;
end
BgLike_den(o,o)=sum_temp;
sum_temp=0;
end
for r=1:N
BgLike(r,1)= BgLike_num(r,r)/BgLike_den(r,r);
end
%%%%Calculation of Foreground likelihood for each superpixels stores in "FgLike"
FgLike=zeros(N,1);
for s=1:N
for t=1:N
FgLike(s,1)=(exp(-BgLike(t,1))) * Euc(s,t)+ FgLike(s,1);
end
end
The above codes are prerequisite for the following sections (in fact, they produce necessary data and matrices for the next section. The aforementioned codes provided to make the whole process reproducible).
Specifically, I think that this section did not give the desired results. I'm afraid I did not properly simulate the parallelism using for loops. Moreover, the terminating conditions (employed with for and if statements to simulate do-while loop) are never satisfied and the loops continue until the last iteration (instead terminating when a specified condition occurs). A major concern here is that if the terminating conditions are properly implemented.
The pseudo algorithm for the following code is as the image below:
%%parallel operations for background and foreground implemented here
T0 = 0 ;
Tf = 20 ;
Ts = 0.1 ;
Ti = T0:Ts:Tf ;
Nt=numel(Ti);
Y_Bg=zeros(N,Nt);
Y_Fg=zeros(N,Nt);
P_Back_Bg=zeros(N,N);
P_Back_Fg=zeros(N,N);
u_Bg=zeros(N,Nt);
u_Fg=zeros(N,Nt);
u_Bg_Star=zeros(N,Nt);
u_Fg_Star=zeros(N,Nt);
u_Bg_Normalized=zeros(N,Nt);
u_Fg_Normalized=zeros(N,Nt);
tau=0.1;
sigma_Bg=zeros(Nt,N);
Temp_Bg=0;
Temp_Fg=0;
C_Bg=zeros(Nt,N);
C_Fg=zeros(Nt,N);
%%System Initialization
for u=1:N
u_Bg(u,1)=(BgLike(u,1)- min(BgLike(:)))/(max(BgLike(:))- min(BgLike(:)));
u_Fg(u,1)=(FgLike(u,1)- min(FgLike(:)))/(max(FgLike(:))- min(FgLike(:)));
end
%% P_state and P_input
P_state=G*W;
P_input=eye(N)-G;
% State Initialization
X_Bg=zeros(N,Nt);
X_Fg=zeros(N,Nt);
for v=1:20 % v starts from 1 because we have no matrices with 0th column number
%The first column of X_Bg and X_Fg is 0 for system initialization
X_Bg(:,v+1)=P_state*X_Bg(:,v) + P_input*u_Bg(:,v);
X_Fg(:,v+1)=P_state*X_Fg(:,v) + P_input*u_Fg(:,v);
v=v+1;
if v==2
C_Bg(1,:)=1;
C_Fg(1,:)=1;
else
for w=1:N
for x=1:N
Temp_Fg=S(w,x)*X_Fg(x,v-1)+Temp_Fg;
Temp_Bg=S(w,x)*X_Bg(x,v-1)+Temp_Bg;
end
C_Fg(v-1,w)=inv(X_Fg(w,v-1)+((Temp_Bg)/(Temp_Fg)*(1-X_Fg(w,v-1))));
C_Bg(v-1,w)=inv(X_Bg(w,v-1)+((Temp_Fg)/(Temp_Bg))*(1-X_Bg(w,v-1)));
Temp_Bg=0;
Temp_Fg=0;
end
end
P_Bg=diag(C_Bg(v-1,:));
P_Fg=diag(C_Fg(v-1,:));
Y_Bg(:,v)= P_Bg*X_Bg(:,v);
Y_Fg(:,v)= P_Fg*X_Fg(:,v);
for y=1:N
Temp_sig_Bg=0;
Temp_sig_Fg=0;
for z=1:N
Temp_sig_Bg = Temp_sig_Bg +S(y,z)*abs(Y_Bg(y,v)- Y_Bg(z,v));
Temp_sig_Fg = Temp_sig_Fg +S(y,z)*abs(Y_Fg(y,v)- Y_Fg(z,v));
end
if Y_Bg(y,v)>= Y_Bg(y,v-1)
sign_Bg=1;
else
sign_Bg=-1;
end
if Y_Fg(y,v)>= Y_Fg(y,v-1)
sign_Fg=1;
else
sign_Fg=-1;
end
sigma_Bg(v-1,y)=sign_Bg*Temp_sig_Bg;
sigma_Fg(v-1,y)=sign_Fg*Temp_sig_Fg;
end
%Calculation of P_Back for background and foreground
P_Back_Bg=tau*diag(sigma_Bg(v-1,:));
P_Back_Fg=tau*diag(sigma_Fg(v-1,:));
u_Bg_Star(:,v)=u_Bg(:,v-1)+P_Back_Bg*Y_Bg(:,v);
u_Fg_Star(:,v)=u_Fg(:,v-1)+P_Back_Fg*Y_Fg(:,v);
for aa=1:N %Normalization of u_Bg and u_Fg
u_Bg(aa,v)=(u_Bg_Star(aa,v)- min(u_Bg_Star(:,v)))/(max(u_Bg_Star(:,v))-min(u_Bg_Star(:,v)));
u_Fg(aa,v)=(u_Fg_Star(aa,v)- min(u_Fg_Star(:,v)))/(max(u_Fg_Star(:,v))-min(u_Fg_Star(:,v)));
end
if (max(abs(Y_Fg(:,v)-Y_Fg(:,v-1)))<=0.0118) &&(max(abs(Y_Bg(:,v)-Y_Bg(:,v-1)))<=0.0118) %% epsilon= 0.0118
break;
end
end
Finally, the saliency map will be generated by using the following codes.
K=4;
T=0.4;
phi_1=(2-(1-T)^(K-1))/((1-T)^(K-2));
phi_2=(1-T)^(K-1);
phi_3=1-phi_1;
for bb=1:N
Y_Output_Preliminary(bb,1)=Y_Fg(bb,v)/((Y_Fg(bb,v)+Y_Bg(bb,v)));
end
for hh=1:N
Y_Output(hh,1)=(phi_1*(T^K))/(phi_2*(1-Y_Output_Preliminary(hh,1))^K+(T^K))+phi_3;
end
V_rs=zeros(N);
V_Final=zeros(rows,columns);
for cc=1:rows
for dd=1:columns
V_rs(cc,dd)=Y_Output(L(cc,dd),1);
end
end
maxDist = 10; % Maximum chessboard distance from image
wSF=zeros(rows,columns);
wSB=zeros(rows,columns);
% Get the range of x and y indices who's chessboard distance from pixel (0,0) are less than 'maxDist'
xRange = (-(maxDist-1)):(maxDist-1);
yRange = (-(maxDist-1)):(maxDist-1);
% Create a mesgrid to get the pairs of (x,y) of the pixels
[pointsX, pointsY] = meshgrid(xRange, yRange);
pointsX = pointsX(:);
pointsY = pointsY(:);
% Remove pixel (0,0)
pixIndToRemove = (pointsX == 0 & pointsY == 0);
pointsX(pixIndToRemove) = [];
pointsY(pixIndToRemove) = [];
for ee=1:rows
for ff=1:columns
% Get a shifted copy of 'pointsX' and 'pointsY' that is centered
% around (x, y)
pointsX1 = pointsX + ee;
pointsY1 = pointsY + ff;
% Remove the the pixels that are out of the image bounds
inBounds =...
pointsX1 >= 1 & pointsX1 <= rows &...
pointsY1 >= 1 & pointsY1 <= columns;
pointsX1 = pointsX1(inBounds);
pointsY1 = pointsY1(inBounds);
% Do stuff with 'pointsX1' and 'pointsY1'
wSF_temp=0;
wSB_temp=0;
for gg=1:size(pointsX1)
Temp=exp(-OMG1*(sqrt(double(A(pointsX1(gg),pointsY1(gg),1))-double(A(ee,ff,1)))^2+(double(A(pointsX1(gg),pointsY1(gg),2))-double(A(ee,ff,2)))^2 + (double(A(pointsX1(gg),pointsY1(gg),3))-double(A(ee,ff,3)))^2));
wSF_temp=wSF_temp+(Temp*V_rs(pointsX1(gg),pointsY1(gg)));
wSB_temp=wSB_temp+(Temp*(1-V_rs(pointsX1(gg),pointsY1(gg))));
end
wSF(ee,ff)= wSF_temp;
wSB(ee,ff)= wSB_temp;
V_Final(ee,ff)=V_rs(ee,ff)/(V_rs(ee,ff)+(wSB(ee,ff)/wSF(ee,ff))*(1-V_rs(ee,ff)));
end
end
imshow(V_Final,[]); %%Saliency map of the image
Part of your terminating criterion is this:
max(abs(Y_a(:,t)-Y_a(:,t-1)))<=eps
Say Y_a tends to 2. You are really close... In fact, the closest you can get without subsequent values being identical is Y_a(t)-Y_a(t-1) == 4.4409e-16. If the two values were any closer, their difference would be 0, because this is the precision with which floating-point values can be represented. So you have reached this fantastic level of closeness to your goal. Subsequent iterations are changing the target value by the smallest possible amount, 4.4409e-16. But your test is returning false! Why? Because eps == 2.2204e-16!
eps is short-hand for eps(1), the difference between 1 and the next representable larger value. Because how floating-point values are represented, this difference is half the difference between 2 and the next representable larger value (which is given by eps(2).
However, if Y_a tends to 1e-16, subsequent iterations could double or halve the value of Y_a and you'd still meet the stopping criterion!
Thus, what you need is to come up with a reasonable stopping criterion that is a fraction of the target value, something like this:
max(abs(Y_a(:,t)-Y_a(:,t-1))) <= 1e6 * eps(max(abs(Y_a(:,t))))
Unsolicited advice
You should really look into vectorized operations in MATLAB. For example,
for y=1:N
Temp_sig_a=0;
for z=1:N
Temp_sig_a = Temp_sig_a + abs(Y_a(y,t)- Y_a(z,t));
end
sigma_a(t-1,y)= Temp_sig_a;
end
can be written as
for y=1:N
sigma_a(t-1,y) = sum(abs(Y_a(y,t) - Y_a(:,t)));
end
which in turn can be written as
sigma_a(t-1,:) = sum(abs(Y_a(:,t).' - Y_a(:,t)));
Avoiding loops is not only usually more efficient, but it also leads to shorter code that is easier to read.
Also, this:
P_FB_a = diag(sigma_a(t-1,:));
u_a(:,t) = u_a(:,t-1) + P_FB_a * Y_a(:,t);
is the same as
u_a(:,t) = u_a(:,t-1) + sigma_a(t-1,:).' .* Y_a(:,t);
but of course creating a diagonal matrix and doing a matrix multiplication with so many zeros is much more expensive than directly computing an element-wise multiplication.

Recursive method to find matching rows on grid

I have a grid object which is populated by space objects each containing a value. What I want to do is write a method which takes a space, and a number representing the amount of equal spaces I would like to find, to see if there is anywhere on the grid with x-number of equal spaces in the same direction.
In psuedo-code, the steps I planned are:
Begin at the top-left corner of the grid.
Check each direction (N,S,E,W,NE,NW,SE,SW) for 2 conditions
The space in that direction exists
The value in that space matches the value in the current space
If these conditions all fail I want call the method again, but with the current space as the next space (increasing left >> right & top >> bottom)
If these conditions are satisfied I want to store this value in a list and call the method again to check the matching space only in the direction the current space was found
If the next space finds that its adjacent space does not match, I want to
Quit searching
Return to the first space the method was called with
Check the remaining directions to satify the 2 conditions
Call the method again with the next space if no spaces satisfy (increasing left >> right & top >> bottom)
The function returns when the current space is the bottom right space or the list of matching values is the same length as the value specified
If this were implemented on a tic-tac-toe board like below, I would start at the top left "O". I would check North, fail, check North-East, fail, check East, pass. Once it passes I would move to the next "O" and check only to its East since the current "O" was found to the east of its previous space, which would give me the expected result of finding 3 "O"s.
The other case I want to handle is, if the South-East were checked the space would move to the center, where the center space would check its South-East, notice that "X" does not equal "O", return back to the top-left space, check the remaining directions, then move to the next space down the line and repeat until all spaces are checked or a match is found
My non-recursive implementation of this method is as follows. It loops through each space, and for each space loops through each compass direction and assigns the value repeated 'num' times to the found variable which will return nil if nothing was found, or the value which was repeated 'num' times
def check_for_row_of(num)
found = nil
each_space do |space|
COMPASS.each do |direction|
if num_spaces_in_direction(space.pos, direction) == num
values = get_spaces_by_pattern(space.pos, direction)
found = values.uniq[0] if values.uniq.length == 1 && values.uniq[0] != " "
end
end
end
found
end
If I understood you correctly, I believe the following code answers your question. Please, tell me if it isn't quite what you were thinking.
For ease of reading, I kept the recursive search function separate from the (somewhat clunky) logic that iterates over each cell and direction.
Also, it is worth mentioning that I am calling transpose and reverse on the Array of Arrays so that the grid is easier for humans to read. Lower left is (0, 0) and top right is (2, 2).
def search(grid, x, y, direction, length_to_find, value_to_find=nil)
return true if length_to_find == 0
value_at_location = grid.transpose[x].reverse[y] if grid.transpose[x]
value_to_find ||= value_at_location
return false if value_at_location != value_to_find
y += 1 if direction =~ /N/i
y -= 1 if direction =~ /S/i
x += 1 if direction =~ /E/i
x -= 1 if direction =~ /W/i
search(grid, x, y, direction, length_to_find - 1, value_to_find)
end
def row_of?(grid, length_to_find)
grid.length.times do |row|
grid[0].length.times do |col|
%w[N NE E SE S SW W NW].each do |direction|
if search(grid, row, col, direction, length_to_find)
return true
end
end
end
end
false
end
grid = [
[ "O", "O", "O"],
[ " ", "O", "X"],
[ " ", "X", "X"]
]
puts row_of?(grid, 3)

Paste several images into a bigger one, using conditions and loop (MATLAB)

I built a binary chessboard (tab):
Now I have to put in several pieces (pawns), just like this:
P_1 and P_2 have the same dimension that each block of the chessboard (301x301 px)
like it follows:
P_1 :
P_2:
In another exercise I had to invert the images of row 2, doing this:
P1_neg=double(P_1)*-1+255;
P2_neg=double(P_2)*-1+255;
I obtain this images:
P1_neg:
P2_neg
In the second row I have to paste two kind of pieces: a black pawn with black background (P_1), and a black pawn with white background (P_2).
Each block of the chessboard has 301x301 pixels, and each piece has the same measurements. I have to use only conditions and loops, but I don't know how paste the pieces there.
So, I know for the second row: when the row (i) it even and the column(j) is odd, I have to paste P_1; and when the row is even and the column is also even I have to paste P_2.
My code, is the following one, I hope you can help me :)
for i=1:8 % from 1 to 8 because it have 8 blocks
for j=1:8
if mod(i,2)==0 && mod (j,2)~=0
%paste P_1 (I don't know how do this)
elseif mod(i,2)==0 && mod(j,2)==0
%paste P_2
end
end
end
figure,imshow() % I don't know if I show the chessboard or I have to save the data in another matrix.
I couldn't upload the chessboard with the original resolution, but here it's the code I use
tab=zeros(2408);
for i=0:7
for j=0:7
if mod(i,2)~=0 && mod(j,2)~=0
for avanza_fila=(i*301)+1:(i+1)*301
for avanza_columna= (j*301)+1:(j+1)*301
tab(avanza_fila,avanza_columna)=255;
end
end
elseif mod(i,2)==0 && mod(j,2)==0
for avanza_fila=(i*301)+1:(i+1)*301
for avanza_columna= (j*301)+1:(j+1)*301
tab(avanza_fila,avanza_columna)=255;
end
end
end
end
end
figure, imshow(tab)
Here's my solution to your problem. I would personally avoid for loops, but you said your assignment needs it. I've created a high resolution version of your board that you can get here:
This board is 2408 x 2408, as each chess piece is 301 x 301, on an 8 x 8 grid. You almost have the logic correct. You just need to figure out how exactly to place the tiles on the board. I wrote two for loops where the first for loop uses rows 2 and 7, and the second for loop goes through columns 1 to 8. For either the second or seventh row, we check to see whether the column is even or odd and place the correct chess piece in its corresponding block. I also converted the board and the images to black and white to get rid of any quantization artifacts, as I saw that in the images you have posted. Also, I have renamed your images to how they're named in your post, so it'll be up to you to change the relevant names according to your code that you have written. I have also made a copy of the board in the code so that we don't want to modify the original board called boardCopy. This copy will contain the placed chess pieces in the board. Without further ado, here's the code:
board = imread('boardHigh.png'); %// High-res board
P_1 = im2bw(imread('P_1.png')); %// Load in the pawn pieces
P_2 = im2bw(imread('P_2.png'));
P1_neg = im2bw(imread('P1_neg.png'));
P2_neg = im2bw(imread('P2_neg.png'));
boardCopy = board; %// Make a copy of the board
for row = [2 7]
for col = 1 : 8
if row == 2
if mod(col,2) ~= 0
boardCopy((row-1)*301 + 1 : row*301, (col-1)*301 + 1 : col*301) = P_2;
else
boardCopy((row-1)*301 + 1 : row*301, (col-1)*301 + 1 : col*301) = P_1;
end
else
if mod(col,2) ~= 0
boardCopy((row-1)*301 + 1 : row*301, (col-1)*301 + 1 : col*301) = P1_neg;
else
boardCopy((row-1)*301 + 1 : row*301, (col-1)*301 + 1 : col*301) = P2_neg;
end
end
end
end
figure;
imshow(boardCopy);
This is the board I get with the chess pieces:
Hope this helps and good luck!

Pattern matching – Normalized Correlation

as a part of my homework i need to implement this pattern matching.
the goal is to "Detect as many of the 0's (zeros) as you can in image coins4.tif."
i was given the NGC function. and i need to use it
this is my main.m file
Image = readImage('coins4.tif');
Pattern = readImage('zero.tif');
showImage(Image);
showImage(Pattern);
message = sprintf('Pattern matching Normalized Correlation');
PatternMatching(Image , Pattern);
uiwait(msgbox(message,'Done', 'help'));
close all
this is my PatternMatching function.
function [ output_args ] = PatternMatching( Image , Pattern )
% Pattern matching – Normalized Correlation
% Detect as many of the 0's (zeros) as you can in image coins4.tif.
% Use the 0 of the 10 coin as pattern.
% Use NGC_pm and find good threshold. Display original image with? detected regions marked using drawRect.
% NGCpm(im,pattern);
% drawRect(rectCoors,color);
% rectCoors = [r0,c0,rsize,csize] - r0,c0 = top-left corner of rect.
% rsize = number of rows, csize = number of cols
%
% color = an integer >=1 representing a color in the color wheel
% (curerntly cycles through 8 different colors
showImage(Image);
hold on
res = NGCpm(Image, Pattern);
for i = 1:size(res,1)
for j = 1:size(res,2)
if res(i,j) > 0.9999
drawRect([i j size(Pattern,1) size(Pattern,2)], 5)
end
end
end
end
this is the Given NGCpm.m file
function res=NGC_PM(im,pattern)
[n m]=size(pattern);
[im_row,im_col]=size(im);
if ~(var(pattern(:))==0)
res = normxcorr2(pattern, im);
res=res(n:im_row,m:im_col);
else
res=zeros(size(im)-size(pattern)+1);
end;
res = 1-abs(res); % res = abs(res);
this is the pattern i'm trying to find and the results, i'm getting
i'm trying to find as many "Zeros" as possiable using the zero pattern of the coin 10.
i'm tryingto understand if there is something wrong with my algorithm in the PatternMatching function. since the NGCpm function is already given to me, all i need to do is just loop of the best threshold ,correct?
or do i need to blur the image or the pattern?
this is the fixed version of this function.
function [ output_args ] = patternMatching( Image , Pattern )
% Pattern matching – Normalized Correlation
% Detect as many of the 0's (zeros) as you can in image coins4.tif.
% Use the 0 of the 10 coin as pattern.
% Use NGC_pm and find good threshold. Display original image with? detected regions marked using drawRect.
% NGCpm(im,pattern);
% drawRect(rectCoors,color);
% rectCoors = [r0,c0,rsize,csize] - r0,c0 = top-left corner of rect.
% rsize = number of rows, csize = number of cols
%
% color = an integer >=1 representing a color in the color wheel
% (curerntly cycles through 8 different colors
showImage(Image);
hold on
res = 1-NGCpm(Image, Pattern);
normalized_corellation = uint8(255*res/max(max(res)));
res_thresh = thresholdImage(normalized_corellation,100);
for i = 1:size(res_thresh,1)
for j = 1:size(res_thresh,2)
if res_thresh(i,j) > 0
drawRect([i j size(Pattern,1) size(Pattern,2)], 5)
end
end
end
end

Resources