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
from numpy import random import matplotlib.pyplot as plt import numpy as np import cv2 mat = np.zeros((500,500,3)) def color(): return ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for _ in range(10): x_coord = random.choice(500) y_coord = random.choice(500) color_person = color() cv2.circle(mat, (x_coord, y_coord), 10, color=color_person,thickness=20) plt.imshow(mat)
Advertisement
Answer
You need to create mat
as uint8
type:
mat = np.zeros((500,500,3)), np.uint8)
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:
from numpy import random import matplotlib.pyplot as plt import numpy as np import cv2 mat = np.zeros((500, 500, 3), np.uint8) # Create mat with type uint8 def color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for _ in range(10): x_coord = random.choice(500) y_coord = random.choice(500) color_person = color() cv2.circle(mat, (x_coord, y_coord), 10, color=color_person, thickness=20) plt.imshow(mat) plt.show()