How to generate random 1s and 0s in a matrix array? - python

I have a matrix and it's currently populated with just 1's. How do I make it so it populates with random 1's and 0's?
matrix5x5 = [[1 for row in range (5)] for col in range (5)]
for row in matrix5x5:
for item in row:
print(item,end=" ")
print()
print("")
Output:
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
I want something like:
1 0 0 1 0
0 1 1 1 1
1 0 1 0 1
1 1 0 0 1
0 1 1 1 1
I found something regarding using random.randint(0,1) but I don't know how to change my current code to include the above.

Modifying your code, using the random package (and not the numpy equivalent):
matrix5x5 = [[random.randint(0,1) for _ in range(5)] for _ in range(5)]
for row in matrix5x5:
for item in row:
print(item,end=" ")
print()
print("")
0 1 0 0 1
0 1 0 1 0
0 0 1 1 0
0 0 0 1 0
1 0 0 1 1
But honestly, numpy makes it a lot faster and easier!

If you don't mind using numpy:
>>> import numpy as np
>>> np.random.randint(2, size=(5, 5))
array([[1, 0, 1, 0, 1],
[1, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 1],
[0, 1, 0, 0, 1]])
Numpy arrays support most list operations that involve indexing and iteration, and if you really care, you can turn it back into a list:
>>> np.random.randint(2, size=(5, 5)).tolist()
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 0, 1, 0, 0]]
And, if for some strange reason, you are 100% adamant on using vanilla Python, just use the random module and a list comprehension:
>>> import random
>>> [[random.randint(0,1) for j in range (5)] for i in range (5)]
[[0, 1, 0, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 0, 1], [1, 1, 1, 1, 1]]

You probably want to use numpy. Do the following:
import numpy as np
my_matrix = np.random.randint(2,size=(5,5))
This will create a random 5 by 5 matrix with 0s and 1s.

Related

create a list of lists with a checkerboard pattern

I would like to change the values ​​of this list by alternating the 0 and 1 values ​​in a checkerboard pattern.
table =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
i tried:
for i in range(len(table)):
for j in range(0, len(table[i]), 2): # ho definito uno step nella funzione range
table[i][j] = 0
but for each list the count starts again and the result is:
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
my question is how can I change the loop to form a checkerboard pattern.
I expect the result to be like:
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
for i in range(len(table)):
for j in range(len(table[i])):
if (i+j)%2 == 0:
table[i][j] = 0
output:
[[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0]]
There doesn't appear to be any reliance on the original values in the list. Therefore it might be better to implement something that creates a list in the required format like this:
def checkboard(rows, columns):
e = 0
result = []
for _ in range(rows):
c = []
for _ in range(columns):
c.append(e)
e ^= 1
result.append(c)
return result
print(checkboard(5, 5))
print(checkboard(2, 3))
print(checkboard(4, 4))
Output:
[[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]
[[0, 1, 0], [1, 0, 1]]
[[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]]

How to keep track of row index of the rows I randomly select from a matrix?

I am trying to perform tournament selection in a GA whereby I need select two rows randomly. Is there a way of keeping track of the index values of the 2 random rows I select from the matrix self.population and storing those in variables?
At the moment it just outputs the two random rows but I need to keep track of which rows were selected.
Below is what I have so far although ideally I would like to store both rows I select from my matrix in separate variables.
self.population = [[0 1 1 1 0 0 1 1 0 1]
[1 0 1 1 0 0 0 1 1 1]
[0 0 0 0 0 1 1 0 0 0]
[1 1 0 0 1 1 1 0 1 1]
[0 1 0 1 1 1 1 1 1 0]
[0 0 0 0 1 0 1 1 1 0]]
def tournament_select(self):
b = np.random.randint(0, self.population[0], 2)
return self.population[b]
Is this what you're looking for?
from random import sample
import numpy as np
population = np.array([[0, 1, 1, 1, 0, 0, 1, 1, 0, 1],
[1, 0, 1, 1, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
[1, 1, 0, 0, 1, 1, 1, 0, 1, 1],
[0, 1, 0, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 1, 0]])
def tournament_select():
row_indices = sample(range(len(population)), k=2)
return row_indices, population[row_indices]
row_indices, candidates = tournament_select()
print(row_indices)
print(candidates)
Output:
[2, 3]
[[0 0 0 0 0 1 1 0 0 0]
[1 1 0 0 1 1 1 0 1 1]]

In opencv how do I get a list of segemented regions

I'm working on a project where I want to evaluate certain parameters on regions of a segemented image. So I have the following code
col = cv2.imread("in.jpg",1)
col=cv2.resize(col,(width,height),interpolation=cv2.INTER_CUBIC)
res=cv2.pyrMeanShiftFiltering(col,20,45,3)
and would now like to somehow get a list of masks per region in res.
So for example if res was now something like this
1 1 0 2 1
1 0 0 2 1
0 0 2 2 1
I would like to get an output such as
1 1 0 0 0
1 0 0 0 0
0 0 0 0 0
,
0 0 1 0 0
0 1 1 0 0
1 1 0 0 0
,
0 0 0 1 0
0 0 0 1 0
0 0 1 1 0
,
0 0 0 0 1
0 0 0 0 1
0 0 0 0 1
So that is a mask for each group of the same values that are connected. Maybe this could somehow involve the floodfill function? I can
see that maybe by looping over every pixel and then flood filling and comparing to see if that set of pixels was already set might work but that seems like a very expensive way so is there something faster?
Oh and here is an example image of res after the code has run
Here's one approach with cv2.connectedComponents -
def list_seg_regs(a): # a is array
out = []
for i in np.unique(a):
ret, l = cv2.connectedComponents((a==i).astype(np.uint8))
for j in range(1,ret):
out.append((l==j).astype(int)) #skip .astype(int) for bool
return out
Sample run -
In [53]: a = np.array([
...: [1, 1, 0, 2, 1],
...: [1, 0, 0, 2, 1],
...: [0, 0, 2, 2, 1]])
In [54]: out = list_seg_regs(a)
In [55]: out[0]
Out[55]:
array([[0, 0, 1, 0, 0],
[0, 1, 1, 0, 0],
[1, 1, 0, 0, 0]])
In [56]: out[1]
Out[56]:
array([[1, 1, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
In [57]: out[2]
Out[57]:
array([[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1]])
In [58]: out[3]
Out[58]:
array([[0, 0, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0]])

How to translate / shift a numpy array?

I am not sure what key-word to search for so if it has been already asked please link the response and close this thread.
I am trying to shift the non-zero entries of a numpy array by a fixed direction, for instance, imagine I have a 2d array:
0 1 2 0
0 3 0 0
0 0 0 0
0 0 0 0
Shifting it by (1,1) would produce the following array:
0 0 0 0
0 0 1 2
0 0 3 0
0 0 0 0
Let's say if the non-zero entries goes out of bound they're simply dropped. How might I do this?
edit: aparently some duplicate from this? Shift elements in a numpy array
I don't really see why are they the same question at all because that one talks about looping the things out of bound around, so it's more of a "rolling" action rather than shifting. Also I liked the solution here, it is very simple and readable.
edit again: fixed some formats
Using roll method from numpy.
>>> import numpy as np
>>> m
array([[0, 1, 2, 0],
[0, 3, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> m = np.roll(m, 1, axis=0) # shift 1 place in horizontal axis
>>> m = np.roll(m, 1, axis=1) # shift 1 place in vertical axis
>>> m
array([[0, 0, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 0],
[0, 0, 0, 0]])
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.roll.html
To simply manage the edges, you can enlarge your array in a bigger one :
square=\
array([[0, 2, 2, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int64)
n,m=square.shape
bigsquare=np.zeros((3*n,3*m),square.dtype)
bigsquare[n:2*n,m:2*m]=square
Then shift is just a view :
def shift(dx,dy):
x=n-dx
y=m-dy
return bigsquare[x:x+n,y:y+m]
print(shift(1,1))
#[[0 0 0 0]
# [0 0 2 2]
# [0 0 2 0]
# [0 0 0 0]]

Select two rows from bit array based on int array python

I have two arrays one Int, and one is bit
s = [ [1] x = [ [1 0 0 0 0]
[4] [1 1 1 1 0]
[9] [0 1 1 1 0]
[0] [0 0 1 0 0]
[3] ] [0 1 1 0 0]]
I want to find the smallest two elements in s (random given) then (select and print) two rows from x (random given) based on s array,
for example, the smallest elements in s[i] are s[3]=0, s[0]=1, so i want to select x[3][0 0 1 0 0], and x[0][1 0 0 0 0]
import numpy as np
np.set_printoptions(threshold=np.nan)
s= np.random.randint(5, size=(5))
x= np.random.randint (2, size=(5, 5))
print (s)
print (x)
I tried my best using the "for loop" but no luck, any advice will be appreciated.
You can use numpy.argpartition to find out the index of the two smallest elements from s and use it as row index to subset x:
s
# array([3, 0, 0, 1, 2])
x
# array([[1, 0, 0, 0, 1],
# [1, 0, 1, 1, 1],
# [0, 0, 1, 0, 0],
# [1, 0, 0, 1, 1],
# [0, 0, 1, 0, 1]])
x[s.argpartition(2)[:2], :]
# array([[1, 0, 1, 1, 1],
# [0, 0, 1, 0, 0]])

Categories