I am using the following example code to create image masks. The masks need to have one of 6 colours - 5 given colours and white background. However when I look at the unique colours of an image saved using code below, there are 25 colours generated. Using matplotlib is there a way to limit the colours generated on save?
def rect(x,y,w,h,c):
ax = plt.gca()
polygon = plt.Rectangle((x,y),w,h,color=c)
ax.add_patch(polygon)
X = np.arange(0,10,0.1)
F = np.zeros(int(len(X)/5))
for f in range(1,5):
Fn=np.full(int(len(X)/5), f, dtype=int)
F = np.append(F, Fn, axis=0)
Y = np.sin(X)
plt.plot(X,Y, alpha=0.0)
plt.xlim([0, 10])
dx = X[1]-X[0]
ccc = ['#996633','blue','yellow','red','green']
cmap = colors.ListedColormap(ccc[0:len(ccc)], 'indexed')
for n, (x,y, f) in enumerate(zip(X,Y,F)):
color = cmap(int(f))
rect(x,0,dx,y,color)
plt.axis('off')
plt.savefig(f'5_colours_only.png', transparent = False, bbox_inches = 'tight', pad_inches = 0)
code to test image colours:
def get_unique_colours(img_name):
im = pil_image.open(img_name)
by_color = defaultdict(int)
for pixel in im.getdata():
by_color[pixel] += 1
return by_color

matplotlib.patches.Patchobjects have the bool keywordantialiased, assumingrecthere is amatplotlib.patches.Rectangleobject (whose base class ismatplotlib.patches.Patch) then you should be able to passantialiased=Falsein their construction