I would like to draw circles in a loop. I want each circle to have a different color, but when I do this, I only get one color.
I tried the code on colab 4.1.2
JavaScript
x
17
17
1
from numpy import random
2
import matplotlib.pyplot as plt
3
import numpy as np
4
import cv2
5
6
mat = np.zeros((500,500,3))
7
def color():
8
return ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
9
10
for _ in range(10):
11
x_coord = random.choice(500)
12
y_coord = random.choice(500)
13
color_person = color()
14
cv2.circle(mat, (x_coord, y_coord), 10, color=color_person,thickness=20)
15
16
plt.imshow(mat)
17
Advertisement
Answer
You need to create mat
as uint8
type:
JavaScript
1
2
1
mat = np.zeros((500,500,3)), np.uint8)
2
matplotlib
conversion is:
- NumPy arrays of type
float
applies pixel range [0, 1]. - NumPy arrays of type
uint8
applies pixel range [0, 255].
You are using plt.imshow(mat)
, when type of mat
is float
.
All values above or equal 1.0
, are at maximum intensity (equivalent to 255
in uint8
).
RGB triplet at maximum intensity applies white color.
Complete code:
JavaScript
1
19
19
1
from numpy import random
2
import matplotlib.pyplot as plt
3
import numpy as np
4
import cv2
5
6
mat = np.zeros((500, 500, 3), np.uint8) # Create mat with type uint8
7
8
def color():
9
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
10
11
for _ in range(10):
12
x_coord = random.choice(500)
13
y_coord = random.choice(500)
14
color_person = color()
15
cv2.circle(mat, (x_coord, y_coord), 10, color=color_person, thickness=20)
16
17
plt.imshow(mat)
18
plt.show()
19