1

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)

enter image description here

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
6
  • Can you add the image that is generated with 25 colors? Commented Dec 8, 2019 at 7:18
  • Image added, bulk of colours are the 5 generated plus white but there are 160 pixels or so of nearly the same colour but not exacltly as specified. Commented Dec 8, 2019 at 8:24
  • Unless I’m mistaken they are occurring at the boundaries between colors? Commented Dec 8, 2019 at 8:27
  • Yes, may be due to antialiasing? I couldn't find a way to disable in matplotlib Commented Dec 8, 2019 at 8:29
  • matplotlib.patches.Patch objects have the bool keyword antialiased, assuming rect here is a matplotlib.patches.Rectangle object (whose base class is matplotlib.patches.Patch) then you should be able to pass antialiased=False in their construction Commented Dec 8, 2019 at 8:35

1 Answer 1

1

It would appear the extra colors are generated by the antialiasing, matplotlib.patches.Patch objects (which matplotlib.patches.Rectangle objects inherit) support disabling this via the bool keyword antialising, so

plt.Rectangle((x,y),w,h,color=c,antialiased=False)

should prevent this.

This can also be done after construction via the method

polygon.set_antialiased()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.